【发布时间】:2017-01-03 08:18:15
【问题描述】:
我正在尝试在 Typescript 中实现类似这个示例:
const appleOption:string = 'Apple';
const orangeOption:string = 'Orange';
export type FruitType = appleOption | orangeOption //the compiler wouldn't allow this.
//my intention is for writing of the type be in variable and not their actual strings so that it's easier for me to refactor them in future
const eventType:FruitType = orangeOption;
我希望使用变量而不是将联合类型输入为 FruitType 的文字字符串,以便当我需要再次使用该值时,我不必将它们重写为魔术字符串,但是作为变量,我可以在以后轻松重构。我试图看看是否可以替代 Typescript 中的数字枚举。
是否可以将变量的值用作联合类型选项之一?
【问题讨论】:
-
听起来你想要一个
enum。 -
@ssube 是的,但是一个字符串枚举,这是我想要模拟的。
-
如果我理解你想要做什么,答案是否定的,你不能,至少不像你想要做的那样。
标签: javascript typescript typescript-typings