如何将字符串的打字稿类型转换为字符串数组?

Die*_*rdk 19 javascript types typescript

我有这种类型:

type myCustomType = "aaa" | "bbb" | "ccc";
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为这样的数组:

["aaa", "bbb", "ccc"]
Run Code Online (Sandbox Code Playgroud)

我怎样才能在打字稿中做到这一点?

Cer*_*nce 18

类型在发出的代码中不存在 - 你不能从类型数组

但在某些情况下,你可以反过来。如果数组不是动态的(或者它的值可以在初始化时完全由类型检查器确定),您可以声明数组as const(这样数组的类型是["aaa", "bbb", "ccc"]而不是string[]),然后从它创建一个类型映射其值来自arr[number]

const arr = ["aaa", "bbb", "ccc"] as const;
type myCustomType = typeof arr[number];
Run Code Online (Sandbox Code Playgroud)

这是操场上的一个例子。

  • 它计算出“arr[0]”、“arr[1]”等的并集;`arr[someNumber]` 其中 `someNumber` 是一个数字。它只是 TypeScript 语法,而不是 JS。 (6认同)
  • @adrisons 它阻止 TypeScript 自动将类型扩展为 `string[]`,而是将其保留为 `["aaa", "bbb", "ccc"]` 的静态元组 (6认同)

Moh*_*lah 9

例如:

  const themeMode = ['light', 'dark'] as const;
  type MainTheme = typeof themeMode[number];
  const values = [...themeMode];

  // iterate on themeMode as const assertion
  values.map((theme) => console.log(theme));
Run Code Online (Sandbox Code Playgroud)