Close
Close full mode
logoWebDevAssist

Introduction to union type in TypeScript

Introduction to union type in TypeScript:

Union type is not a type actually. We can use union type with more than two types, or to combine multiple types.

In this post, I will show you how to use union type in TypeScript with examples.

YouTube video:

I published one video on YouTube on union type. You can watch it here:

Example of union type:

Let's take a look at the below example:

let myVar: string;
myVar = 'hello';
myVar = 20;

In this example, myVar is initialized as string type. It is assigned hello. But the last line is trying to assign a number to this variable. Since this is a string variable, we can't assign a number to it. It will throw an error.

We can use union type to fix this problem. We can create a type that is string or number type. Pipe symbol, | is used for union type.

So, if we use string | number, it will represent string or number.

let myVar: string|number;
myVar = 'hello';
myVar = 20;

It will remove the error because myVar can be a string or a number.

Example with function:

Let's try it with a function.

For the below program:

function printVariable(v: string | number) {
if (typeof v === 'string') {
console.log(`${v} is a string`);
} else {
console.log(`${v} is a number`);
}
}
printVariable('hello');
printVariable(10);
  • printVariable is a function with one parameter of type string | number. It can be a string or a number.
  • Inside this function, we are checking the type of it and based on its type, it is printing a message.
  • printVariable is called with a string and a number.

If you run this program, it will print the below output:

hello is a string
10 is a number

Example of union type in parsing network response:

We can use union types in many places. Let's say we want to use it in parsing network responses.

Suppose, the network response can be 'success', 'pending' or 'failed'. For success, it also includes a number as the data.

{
status: 'success'
data: {
result: 20
}
}
{
status: 'failed'
}
{
status: 'pending'
}

We can create three types for each of these responses and we can use union type to combine these three types.

type ResponseSuccessType = {
status: string;
data: {
result: number;
}
};
type ResponseFailedType = {
status: string;
};
type ResponsePendingType = {
status: string;
};
type ResType = ResponseSuccessType | ResponseFailedType | ResponsePendingType;
function parseResponse(res: ResType) {
if (res.status === 'success') {
console.log(`Response is success, ${(res as ResponseSuccessType).data.result}}`)
} else if (res.status === 'error') {
console.log('Response failed!!')
} else if (res.status === 'pending') {
console.log('Response is pending!!')
}
}
parseResponse({ status: 'error' });
parseResponse({ status: 'pending' });
parseResponse({ status: 'success', data: { result: 10 } });
  • ResponseSuccessType, ResponseFailedType and ResponsePendingType are these three types.
  • The ResType is the union type of these three types.
  • parseResponse function takes one parameter of type ResType.
  • Based on the value of status, it prints different messages or it parses the response in different ways.
  • The last three lines are calling the parseResponse method with different types of response data. If you run this program, it will give you the below results:
Response failed!!
Response is pending!!
Response is success, 10}

Subscribe to our Newsletter

Previous
Introduction to types in typescript
Next
Introduction to object type in TypeScript