Carven Carven -4 years ago 223
TypeScript Question

Is it possible to use variable values as one of the union types in Typescript?

I'm trying to achieve something like this example in 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;

Instead of typing out the union types as literal strings for
, I'm hoping to use variables so that when I need to use the value again, I don't have to rewrite them out as magic strings, but as variables which I can refactor easily at a later time. I was trying to see if I could have an alternative to numeric enums in Typescript.

Is it possible to make use of a variable's value as one of the union type options?

Answer Source

If you don't want to use Enums, you can define an actual string as one of the union types:

type FruitType = 'orange' | 'apple' | 'banana'
let validFruit: FruitType = 'orange' // compiles fine
let invalidFruit: FruitType = 'tomato' // fails compilation

Or if you want to have a separate type for every string:

type OrangeType = 'orange'
type AppleType = 'apple'
type FruitType = OrangeType | AppleType
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download