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)
这是操场上的一个例子。
例如:
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)
| 归档时间: |
|
| 查看次数: |
5907 次 |
| 最近记录: |