是否可以将变量值用作 Typescript 中的联合类型之一?

Car*_*ven 6 javascript typescript typescript-typings

我正在尝试在 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; 
Run Code Online (Sandbox Code Playgroud)

FruitType我希望使用变量,而不是将联合类型输入为文字字符串,这样当我需要再次使用该值时,我不必将它们重写为魔术字符串,而是将它们重写为可以重构的变量很容易在以后的时间。我试图看看我是否可以在 Typescript 中找到数字枚举的替代方案。

是否可以将变量的值用作联合类型选项之一?

Pel*_*obs 6

如果不想使用枚举,可以将实际字符串定义为联合类型之一:

type FruitType = 'orange' | 'apple' | 'banana'
let validFruit: FruitType = 'orange' // compiles fine
let invalidFruit: FruitType = 'tomato' // fails compilation
Run Code Online (Sandbox Code Playgroud)

或者,如果您想为每个字符串使用单独的类型:

type OrangeType = 'orange'
type AppleType = 'apple'
type FruitType = OrangeType | AppleType
Run Code Online (Sandbox Code Playgroud)