TypeScript: Union Types – Multiple types for a variable

Union Type definition in TypeScript allows us to have multiple types for a variable. For example, we can have the type of string and number for a variable. So this variable accepts both strings as well as numbers without any errors.

example 1 :

let index : string | number;

index = 'not available';
index = 14;

Here in the above example, we have a variable called index. And we have defined two types for its string and number. So our variable index can accept value either string or number.

Firstly the value is taken as a string – ‘not available’

then we are able to replace the same with value 14 , which is an integer.

example 2:

let username: string | string[];

In the second example we have a variable username with type string or array of strings. So its ready to accept single name or multiple names.

So this is how the union type definitions in TypeScript work. In certain cases, we may encounter such requirements of accepting values of multiple data types.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published.