Literal types in TypeScript allow developers to specify exact values that a variable can hold. This feature enhances type safety and provides more precise control over the values that can be assigned to a variable. By using literal types, developers can define variables that can only be assigned specific string, number, or boolean values, which can help prevent bugs and improve code readability.
Literal types can be particularly useful when working with APIs, state management, or any scenario where a variable should only accept a limited set of values. They can be used in conjunction with union types to create more complex types that still maintain strict value constraints.
String literal types allow you to specify exact string values that a variable can hold. For example:
type Direction = 'left' | 'right' | 'up' | 'down';
let move: Direction;
move = 'left'; // Valid
move = 'right'; // Valid
move = 'forward'; // Error: Type '"forward"' is not assignable to type 'Direction'.
Numeric literal types work similarly to string literal types, allowing you to define variables that can only take specific numeric values:
type StatusCode = 200 | 404 | 500;
let responseCode: StatusCode;
responseCode = 200; // Valid
responseCode = 404; // Valid
responseCode = 300; // Error: Type '300' is not assignable to type 'StatusCode'.
Boolean literal types restrict a variable to either `true` or `false`:
type IsActive = true | false;
let activeStatus: IsActive;
activeStatus = true; // Valid
activeStatus = false; // Valid
activeStatus = null; // Error: Type 'null' is not assignable to type 'IsActive'.
In conclusion, literal types in TypeScript provide a powerful way to enforce strict value constraints on variables, enhancing type safety and code clarity. By understanding and applying these concepts, developers can write more reliable and maintainable code.