Literal types là type chính xác là một giá trị cụ thể: type Direction = 'left' | 'right' | 'up' | 'down' — chỉ chấp nhận đúng 4 giá trị đó.
- Kết hợp với union tạo enum-like types mà không có runtime overhead của enum thật.
Ví dụ thực tế: type Status = 'loading' | 'success' | 'error' cho API state.
Literal types are types that are exactly a specific value: type Direction = 'left' | 'right' | 'up' | 'down' — only those 4 values are accepted.
- Combined with union, they create enum-like types without the runtime overhead of real enums.
- Practical example:
type Status = 'loading' | 'success' | 'error'for API state. - Trap: TypeScript infers
let dir = 'left'asstring, not as a literal — useconstoras constto preserve the literal type. - They are the foundation of discriminated unions and type narrowing.