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

时间:2020-01-22 10:09:20

标签: javascript typescript types

我有这种类型:

type myCustomType = "aaa" | "bbb" | "ccc";

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

["aaa", "bbb", "ccc"]

如何在打字稿中做到这一点?

2 个答案:

答案 0 :(得分:4)

类型在发出的代码中不存在-您不能从 type 转换为 array

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

const arr = ["aaa", "bbb", "ccc"] as const;
type myCustomType = typeof arr[number];

下面是一个示例on the playground

答案 1 :(得分:1)

您不能使用字符串文字,但可以使用枚举

enum MyEnum {
  "aaa",
  "bbb",
  "ccc",
}

Object.keys(MyEnum).forEach(key => {
  console.log(key);
})

此处复制:https://stackblitz.com/edit/typescript-uqvach