typescript - 是否可以构建自定义内在类型?
问题描述
由于模板文字落在 Typescript ( PR ) 中,我们可以在我们的类型中访问以下函数:
- 大写
- 小写
- 大写
- 取消大写
有关更多信息,请参阅文档。
知道了这一点,我怀疑我想要实现的目标是不可能的,但如果我只是错过了一些东西,我会问。
我有一个具有一定数量属性的界面......加上一些可以发展的属性。我需要能够在一种类型中提取可以进化的类型。问题是它们带有递增的数字(从 1 到 3)。一个例子会更好理解:
interface A {
propA: string; // not interested in that
propB: string; // not interested in that
propC: string; // not interested in that
propD1: string;
propD2: string;
propD3: string;
propE1: string;
propE2: string;
propE3: string;
propF1: string;
propF2: string;
propF3: string;
}
不知道如何实现它或者是否有可能......但我想要一个这样的类型:
MagicType<A>
应该返回'propD' | 'propE' | 'propF'
。
基本上,它应该能够看到那些以1
, 2
,3
结尾的存在。
很确定我在这里要求太多,但谁知道:)。
虽然这对于现有的模板文字函数(Uppercase
, Lowercase
, Capitalize
, Uncapitalize
)看起来不可行,但我也想知道目前是否可以创建自定义内在类型?
感谢您的任何想法,甚至只是确认它根本不可行
解决方案
“内在”意味着编译器内置,因此严格的答案是您需要分叉编译器。
当然,真正的答案是你不需要你的类型是内在的:
type EasyAs123<K extends string> = K extends `${infer U}${1 | 2 | 3}` ? U : never
// type Test = "propD" | "propE" | "propF"
type Test = EasyAs123<keyof A>
推荐阅读
- r - 在 GBM 的超参数调整中进行网格搜索后,如何获得 Gini 指数以获取 tweedie 损失函数?
- jquery - jQuery添加类不适用于特定的类名
- nosql - N1QL Analytics 查询中子节点的偏移结果
- java - 在 Observer 内的行中找不到可执行代码 - Android Studio gradle 断点
- javascript - 有什么办法可以防止 NodeJS 中出现这个错误?
- python - 从变量中删除空格/逗号以添加到字符串
- batch-file - 批量将文件名添加到每一行并合并子目录中的多个 TXT 文件
- node.js - 从另一个应用程序运行 Angular 应用程序的部分部分
- asp.net - 什么触发了带有 ClientValidationFunction 的 CustomValidator?
- javascript - 在 Promise 中模拟和断言函数调用