In TypeScript, string literals allow you to specify the exact value a string
must have in it’s lifespan. You can assume it a form as ‘string based enum’ which also is named group of string
constants.
Syntax
Use ‘pipe’ symbol between different allowed string
values.
type myVar = "value1" | "value2" | "value3" | "value4"; //upto N values //For example type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD";
String Literal types example
Let’s see how we can use string
literal and how we cannot.
Variable Assignment
You can assign only allowed values to 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
You can pass only allowed values to literal type argument. 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
Drop me your questions in comments section.
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.