String Literal Types In TypeScript

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:
  1. let orderStatus: 'CANCELLED' | 'DELIVERED' | 'INTRANSIT' | 'PROCESSING';            
  2.       
  3. orderStatus = 'RETURNED';  // Error: Type '"RETURNED"' is not assignable to type '"CANCELLED" | "DELIVERED" | "INTRANSIT" | "PROCESSING"'.      
  4. 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:
  1. type status = 'CANCELLED' | 'DELIVERED' | 'INTRANSIT' | 'PROCESSING';    
  2.     
  3. let orderStatus: status;    
  4.     
  5. orderStatus = 'RETURNED'// Error: Type '"RETURNED"' is not assignable to type 'status'.    
  6. orderStatus = 'DELIVERED'// ok  
As you can see, we've extracted our string literal types inside an alias called status and using status instead of manually specifying the types. This could also be helpful if you're going to use the same string literal types in multiple places throughout the application.
 
You could also utilize this feature while accepting parameters inside a function:
  1. type status = 'CANCELLED' | 'DELIVERED' | 'INTRANSIT' | 'PROCESSING';        
  2.         
  3. let orderStatus: string;        
  4.         
  5. function setOrderStatus(orderStatusParam: status) {        
  6.     orderStatus = orderStatusParam;        
  7. }        
  8.         
  9. setOrderStatus('RETURNED'); // Argument of type '"RETURNED"' is not assignable to parameter of type 'status'.        
  10. setOrderStatus('CANCELLED'// ok    
As you can see in the above code snippet, if someone tries to assign a value that is not specified in the status alias TypeScript will throw an error.
 
One thing that you need to keep in mind is string literal types are case sensitive.
  1. type status = 'CANCELLED' | 'DELIVERED' | 'INTRANSIT' | 'PROCESSING';          
  2.           
  3. let orderStatus: string;          
  4.           
  5. function setOrderStatus(orderStatusParam: status) {          
  6.     orderStatus = orderStatusParam;          
  7. }          
  8.       
  9. setOrderStatus('cancelled'// Error: Argument of type '"cancelled"' is not assignable to parameter of type 'status'.  
In the above code snippet, even though cancelled and CANCELLED is the same word, the TypeScript compiler will throw an error as the expected string is in uppercase and the parameter we're passing to the function is in lowercase.