我试图在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中替换数字枚举。
是否可以将变量的值用作联合类型选项之一?
答案 0 :(得分:3)
如果您不想使用Enums,可以将实际字符串定义为联合类型之一:
type FruitType = 'orange' | 'apple' | 'banana'
let validFruit: FruitType = 'orange' // compiles fine
let invalidFruit: FruitType = 'tomato' // fails compilation
或者,如果您想为每个字符串分别设置一个类型:
type OrangeType = 'orange'
type AppleType = 'apple'
type FruitType = OrangeType | AppleType