Backbencher.dev

Literal Type in TypeScript

Last updated on 15 Jan, 2023

Instead of saying, a variable can contain a string or a number, literal type forces a particular value to a variable.

Literal type with const

We have a const variable in our code:

const num = 80;

Since a const variable cannot be reassigned, TypeScript marks the type of num as 80(Not number).

const num: 80;

That was an example of literal type.

Combining literal types using or operator

If a variable can have only two values apple or banana, we can set the type as follows:

let a: "apple" | "banana";
--- ○ ---
Joby Joseph
Web Architect