1

我正在尝试获取类型的长度,但只需使用这样的变量:const testTypeLength = 4;

我想知道打字稿是否有可能:

  type Test = "T" | "e" | "s" | "t";
  console.log(Test.length)
4

1 回答 1

2

类型仅存在于编译类型并在编译期间被擦除。因此不能基于类型创建 javascript 值(TS 中的指导原则之一是编译器不应执行任何类型定向发出,它只是检查类型是否有效并删除类型)

但是,您可以反过来,从值到类型。因此,您可以从数组开始并获取Test类型。并且拥有数组,您可以获得所需的length或任何其他值:

const Test = ["T", "e", "s", "t"] as const
type Test = typeof Test[number]; // same as before ( type Test = "T" | "e" | "s" | "t") but extracted from the const
console.log(Test.length) // ok accesing the const Test

游乐场链接

于 2019-11-25T09:03:26.970 回答