Skip to main content

Union in Typescript

Updated 1 min readMarkdown
Part of seriesTypescript

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";

No comments yet. Be the first to comment.

Typescript

Part 4 of 4

In this series, I will be providing good stuffs about typescript that will help you to learn typescript better from the start.

Start from the beginningThings to learn when you are starting new in TypescriptLets get started with Typescript