How to set more than one type for a variable in TypeScript?

September 21, 2021 - 3 min read

To set more than one type for a variable, we can define a union type for the variable.

Union types contain more than one type separated by the | symbol (vertical slash).

TL;DR

// union type declaration
let nums: string | number;

// assign a string value
nums = "1000"; // ✅ allowed

// assign a number value
nums = 200; // ✅ also allowed

// try to assign a value which is
// neither a string nor a number type
nums = true; // ❌ not allowed. Type 'boolean' is not assignable to type 'string | number'.

For example, Let's say we have a variable called nums and want to hold values of both the string type and the number type. To do that we can use a union type of both the string and the number type.

It can be done like this,

// union type declaration
let nums: string | number;

Now let's try to assign the value 1000 of string type and also the value of 200 of number type to the nums variable like this,

// union type declaration
let nums: string | number;

// assing a string value
nums = "1000"; // ✅ allowed

// assign a number value
nums = 200; // ✅ also allowed

As you can see that the TypeScript compiler allowed us to assign both the string and number value one after the other and doesn't show an error. This is because of the union type we have declared which is made out of the string type and the number type.

Now let's also try to assign a value of boolean type which is not declared in the above union type like this,

// union type declaration
let nums: string | number;

// assign a string value
nums = "1000"; // ✅ allowed

// assign a number value
nums = 200; // ✅ also allowed

// try to assign a value which is
// neither a string nor a number type
nums = true; // ❌ not allowed. Type 'boolean' is not assignable to type 'string | number'.

As you can see that the TypeScript showed us an error saying that Type 'boolean' is not assignable to type 'string | number'. which is what we want to happen.

See the execution of the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.