In TypeScript, literals allow us to specify a set of exact values that a type
can have in it’s lifespan. We can assume a literal as it as an ‘enum’ which is a named group of constants of given type.
Literal types can be of 3 types:
string
number
boolean
1. Literal Type Syntax
Use ‘pipe’ symbol between different allowed values for a given type
literal. For example, below given code is for an string literal.
type myVar = "value1" | "value2" | "value3" | "value4"; type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD"; type countMe = 1 | 2 | 3 | 4 | 5; type result = true | false;
2. Working with Literal Types
To understand better, let’s see how we can use a string
literal and how we cannot.
Variable Assignment
We can assign only one of the allowed values to the literal type variable. Else it will be compile time error.
type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD"; let currStatus: AppStatus; currStatus = "ACTIVE"; //OK currStatus = "DELETED"; //Error - Type '"DELETED"' is not //assignable to type 'AppStatus'
Function Parameter
We can pass only one of the allowed values to literal type argument to a method. Else it will be compile time error.
type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD"; function showMe(currentStatus: AppStatus): void { console.log(currentStatus); } showMe('ACTIVE'); //OK - Print 'ACTIVE' showMe('DELETED'); //Compile time Error
Happy Learning !!
Comments