typescript - 是否可以构建自定义内部类型?

标签 typescript typescript-typings

自从模板字面量出现在 Typescript ( PR ) 中,我们可以在我们的类型中访问以下函数:

  • 大写
  • 小写
  • 大写
  • 取消大写

参见 documentation了解更多。

知道这一点后,我怀疑我想要实现的目标是不可能的,但我会问以防万一我遗漏了什么。

我有一个界面,它有一定数量的属性……加上一些可以进化的属性。我需要能够提取出可以进化的类型。问题是它们带有递增的数字(从 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在最后。

很确定我在这里要求太多,但谁知道:)。

虽然这对于现有的模板文字函数(UppercaseLowercaseCapitalizeUncapitalize)看起来不可行,但我还想知道目前是否可以创建自定义内部类型?

感谢任何想法,甚至只是确认它根本不可行

最佳答案

“内在”意味着内置于编译器中,因此严格的答案是您需要 fork 编译器。

当然真正的答案是你不需要你的类型是内在的:

type EasyAs123<K extends string> = K extends `${infer U}${1 | 2 | 3}` ? U : never

// type Test = "propD" | "propE" | "propF"
type Test = EasyAs123<keyof A>

Playground Link

关于typescript - 是否可以构建自定义内部类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68937638/

相关文章:

TypeScript:如何创建一个类型或接口(interface),它是一个具有 n 个键之一或者是字符串的对象?

typescript - 在 typescript 中定义常量( ionic 应用程序)

typescript - TS : how to get constant Array element type

javascript - Angular 2 : Promise rejection: alertify is not defined

继承类的 typescript 返回类型

TypeScript 和 React Native : Are the type definitions for RN styles wrong?

javascript - 只能包含特定列表中的元素的数组的 typescript 类型

javascript - 表中编辑的数据应该在图表和其他组件中发生变化

javascript - 按位运算在运行时容易失败 typescript

typescript - 使用 this.$parent.somePropOrMethod 和 this.$root.somePropOrMethod 时,属性 X 在类型 'Vue' 上不存在