Literal types are a powerful feature in TypeScript that allow you to specify exact values as types. They provide a way to define more precise and specific types, enhancing type safety and code clarity.
In TypeScript, literal types let you define a type that can only have one specific value. This concept applies to strings, numbers, and booleans. By using literal types, you can create highly specific type definitions that catch potential errors at compile-time.
String literal types allow you to specify exact string values as types. They're particularly useful when you want to restrict a variable to a specific set of strings.
type Direction = "north" | "south" | "east" | "west";
let myDirection: Direction = "north"; // Valid
// let invalidDirection: Direction = "northeast"; // Error
Similar to string literals, numeric literal types let you define specific number values as types. This is helpful when working with fixed numeric values or enumerations.
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 4; // Valid
// let invalidRoll: DiceRoll = 7; // Error
While less common, boolean literal types can be used to create more specific boolean types. They're often combined with other types in union types.
type Comparison = true | false | 0 | 1;
let result: Comparison = true; // Valid
let anotherResult: Comparison = 0; // Also valid
Literal types are often used in combination with Union Types to create powerful, flexible type definitions. This allows for precise control over allowed values while maintaining flexibility.
type Status = "pending" | "processing" | "completed" | 404 | 500;
let currentStatus: Status = "pending"; // Valid
let errorStatus: Status = 404; // Also valid
Literal types in TypeScript provide a powerful way to enhance type safety and code clarity. By specifying exact values as types, you can create more precise and self-documenting code. Whether used alone or in combination with other TypeScript features like Union Types, literal types are an essential tool in the TypeScript developer's toolkit.