Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 353
Carven Avatar asked Aug 26 '16 15:08

Carven


People also ask

How do you declare a union type variable in TypeScript?

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.

Can a variable have multiple types TypeScript?

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.

How do you handle a union type in TypeScript?

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.

What operator would you use in order to specify a union type in TypeScript?

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 ...


1 Answers

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
like image 124
Pelle Jacobs Avatar answered Oct 10 '22 13:10

Pelle Jacobs