Skip to main content

Command Palette

Search for a command to run...

Union in Typescript

Updated
1 min read

Union in typescript allows the variable to hold more than one type of value. It is useful when variable can be of various types. It is defined by | operator between types.

//Simple Union
let randomValue:string|number=12;
randomValue="John Doe";
//randomValue can either be string or number

Union Type with Function

//Union Type with function
function randomFunc(params:string|number){
console.log(`Print ${params}`);
}
randomFunc("John");
randomFunc(12);
//Function accepts string or number as its parameter.

Union Type in Object

In the given example, variable Person can have object with type of Admin or Student.

type Admin={
name:string;
role:string;
}
type Student={
name:string;
id:id
}
let Person : Admin|Student;
Person={
name:"Bob";
role:"Administrator"
}
Person={
name:"Leo",
id:1
}

Union Type in Array

The given example demonstrates an array that can contain both string and number values.

let arrayValue:(string|number)[]=["John Doe",21,"Jason",1,23];

Union Type in Literal Values

In the given example variable requestStatus can have literal string value pending, success or error.

let requestStatus:"pending"|"success"|"error"="pending";
requestStatus="pending";
requestStatus="error";