Introduction
The string literal type feature was introduced in version 1.8 of TypeScript. String literal type lets you specify a group of potential string values that could be assigned to a variable. If someone tries to assign a value that is not specified by the string literal type, TypeScript throws a compile-time error.
Examples
Let's understand this in detail with the help of an example:
- let orderStatus: 'CANCELLED' | 'DELIVERED' | 'INTRANSIT' | 'PROCESSING';
- orderStatus = 'RETURNED'; // Error: Type '"RETURNED"' is not assignable to type '"CANCELLED" | "DELIVERED" | "INTRANSIT" | "PROCESSING"'.
- orderStatus = 'DELIVERED'; // ok
In the above code snippet, the possible values that could be assigned to orderStatus variable are 'CANCELLED', 'DELIVERED', 'INTRANSIT', 'PROCESSING'. When we try to assign 'RETURNED' to the variable, it'll throw an error.
You could also create aliases for your string literal types:
- type status = 'CANCELLED' | 'DELIVERED' | 'INTRANSIT' | 'PROCESSING';
- let orderStatus: status;
- orderStatus = 'RETURNED'; // Error: Type '"RETURNED"' is not assignable to type 'status'.
- orderStatus = 'DELIVERED'; // ok

Join the conversation! Your thoughts help the community grow.