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 FruitType
, 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?
TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.
In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types.
TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.
In TypeScript union types is one of the feature and it is mainly used for to define the user variable which can have multiple set and data types value like integer or number, character, string, float etc these combined data type are referred as union types and it is allowed for the variable with multiple set of data ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With