Typescript 中逗号分隔字符串的真正递归模板文字

如何解决Typescript 中逗号分隔字符串的真正递归模板文字

我正在尝试为包含逗号分隔值的字符串定义 Typescript 模板文字。我能让这个定义真正递归和通用吗?

请参阅 this typescript playground 以对该案例进行实验。

每个逗号分隔值代表一个排序顺序,如 height asc。该字符串应定义一个顺序(包括一级、二级、三级等),根据有效字段名称和两个可能的排序 "asc""desc" 的并集,该顺序可能包含无限多个排序级别,以分隔符分隔根据示例代码中的示例使用逗号。

下面的实现最多可处理 4 个排序顺序,但案例 5 表明它并不是真正的递归。当前扩展 (2x2) 的数量最多只包含 4 个可能的值,所以我很幸运地处理了我尝试过的初始情况。

const FIELD_NAMES = [
  "height","width","depth","time","amaze",] as const;

const SORT_ORDERS = [
  "asc","desc",] as const;

type Field = typeof FIELD_NAMES[number];
type Order = typeof SORT_ORDERS[number];

type FieldOrder = `${Field} ${Order}`
type Separated<S extends string> = `${S}${""|`,${S}`}`;
type Sort = Separated<Separated<FieldOrder>>;

/** SUCCESS CASES */
const sort1:Sort = "height asc"; //compiles
const sort2:Sort = "height asc,depth desc"; //compiles
const sort3:Sort = "height asc,height asc,height asc"; //compiles
const sort4:Sort = "height asc,width asc,depth desc,time asc"; //compiles
const sort5:Sort = "height asc,time asc,amaze desc"; //SHOULD compile but doesn't

/** FAILURE CASES */
const sort6:Sort = "height"; //doesn't compile 
const sort7:Sort = "height asc,"; //doesn't compile
const sort8:Sort = ""; //doesn't compile

我不能再增加这个模板文字的“arity”了,因为尝试像下面那样做 2x2x2 会导致 Expression produces a union type that is too complex to represent

type Sort = Separated<Separated<Separated<FieldOrder>>>;

是否可以定义一个模板文字来处理一般情况?

解决方法

如您所见,您正在创建的 template literal types 类型会迅速破坏编译器表示联合的能力。如果您阅读 pull request that implements template literal types,您会看到联合类型最多只能有 100,000 个元素。因此,您只能让 Sort 接受最多 4 个逗号分隔的值(这将需要大约 11,110 个成员)。而且您当然不能让它接受任意数字,因为这意味着 Sort 需要是一个无限联合,并且无穷大比 100,000 大一些。因此,我们不得不放弃将 Sort 表示为特定联合类型的不可能完成的任务。


通常,my approach 在这种情况下是从特定类型切换到充当 recursive constraints泛型类型。所以我们有Sort而不是ValidSort<T>。如果 T 是有效的排序字符串类型,则 ValidSort<T> 将等同于 T。否则,ValidSort<T> 将是来自 Sort 的一些合理候选(或这些的联合),它“接近”到 T

这意味着您打算编写 Sort 的任何地方现在都需要编写 ValidSort<T> 并将一些泛型类型参数添加到适当的范围。此外,除非您想强迫某人编写 const s: ValidSort<"height asc"> = "height asc";,否则您需要调用一个 helper 函数,例如 asSort(),它检查其输入并推断类型。这意味着你得到 const s = asSort("height asc");

它可能并不完美,但它可能是我们能做到的最好的。


让我们看看定义:

type ValidSort<T extends string> = T extends FieldOrder ? T :
  T extends `${FieldOrder},${infer R}` ? T extends `${infer F},${R}` ?
  `${F},${ValidSort<R>}` : never : FieldOrder;

const asSort = <T extends string>(t: T extends ValidSort<T> ? T : ValidSort<T>) => t;

ValidSort<T> 是一个 recursive conditional type,它检查字符串类型 T 以查看它是 FieldOrder 还是以 FieldOrder 开头的字符串一个逗号和一个空格。如果它是 FieldOrder,那么我们有一个有效的排序字符串,我们只需返回它。如果它以 FieldOrder 开头,那么我们递归地检查字符串的其余部分。否则,我们有一个无效的排序字符串,我们返回 FieldOrder

让我们看看它的实际效果。您的成功案例现在都按预期工作了:

/** SUCCESS CASES */
const sort1 = asSort("height asc"); //compiles
const sort2 = asSort("height asc,depth desc"); //compiles
const sort3 = asSort("height asc,height asc,height asc"); //compiles
const sort4 = asSort("height asc,width asc,depth desc,time asc"); //compiles
const sort5 = asSort(
  "height asc,time asc,amaze desc"); //compiles

并且失败案例失败,错误消息显示您应该使用的“足够接近”类型:

/** FAILURE CASES */
const sort6 = asSort("height"); // error!
/* Argument of type '"height"' is not assignable to parameter of type 
'"height asc" | "height desc" | "width asc" | "width desc" | "depth asc" | 
"depth desc" | "time asc" | "time desc" | "amaze asc" | "amaze desc"'. */

const sort7 = asSort("height asc,"); // error!
/* Argument of type '"height asc,"' is not assignable to parameter of type 
'"height asc" | "height desc" | "width asc" | "width desc" | "depth asc" | 
"depth desc" | "time asc" | "time desc" | "amaze asc" | "amaze desc"'. */

const sort8 = asSort(""); // error!
/* Argument of type '""' is not assignable to parameter of type 
'"height asc" | "height desc" | "width asc" | "width desc" | "depth asc" | 
"depth desc" | "time asc" | "time desc" | "amaze asc" | "amaze desc"'. */

const sort9 = asSort("height asc,death desc"); // error!
/* Argument of type '"height asc,death desc"' is not assignable to parameter of type 
'"height asc,depth desc" | "height asc,height asc" | "height asc,time asc" |
 "height asc,amaze desc" | "height asc,height desc" | "height asc,width asc" | 
 "height asc,width desc" | "height asc,depth asc" | "height asc,time desc" | 
 "height asc,amaze asc"'. */

我添加了 sort9 来向您展示错误消息如何不仅显示 FieldOrder,还显示以 "height asc," 开头,后跟 FieldOrder 的字符串。

Playground link to code

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-