首页 > 解决方案 > 是否可以构建自定义内在类型?

问题描述

由于模板文字落在 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)看起来不可行,但我也想知道目前是否可以创建自定义内在类型?

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

标签: typescripttypescript-typings

解决方案


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

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

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

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

游乐场链接


推荐阅读