获取某种字符串类型的所有类型的列表

时间:2017-04-18 16:49:17

标签: typescript

我有这个打字稿由generateTypeScript-gradle插件生成。

export type FoodUnit = "AS_NEEDED" | "G" | "KG" | "ML" | "L" | "JAR" | "CAN" | "PIECE" | "BUNCH" | "HANDFUL" | "STALK" | "SLICE" | "TABLESPOON" | "TEASPOON" | "DROP" | "CUP" | "TWIG";

现在我想要一个班级中所有可能单位的列表。

  units:FoodUnit[] = ["AS_NEEDED", "G", "KG" .....

有没有办法改为写

  units:FoodUnit[] = FoodUnit.values()
像在Java中一样?

1 个答案:

答案 0 :(得分:1)

您生成的代码使用type关键字,因此生成type alias

export type FoodUnit = "AS_NEEDED" | "G" | "KG" | "ML" | "L" | "JAR" | "CAN" | "PIECE" | "BUNCH" | "HANDFUL" | "STALK" | "SLICE" | "TABLESPOON" | "TEASPOON" | "DROP" | "CUP" | "TWIG";

类型别名纯粹是编译时构造:它们不会以任何形式存在于JS代码中,而是由浏览器或节点实际运行。

如果你想要一个基于字符串的枚举构造,你可以使用像typescript-string-enums这样的库,或者自己做as documented here