In TypeScript, a literal type is a type that represents a single exact value. There are three main types of literal types: string literals, numeric literals, and boolean literals.
A string literal type allows you to specify a particular string value as a type. For example:
let direction: 'north' | 'south' | 'east' | 'west';
direction = 'north'; // This is valid
// direction = 'up'; // This is a compile-time error
In this example, the variable direction
can only be assigned one of the four specified string values.
Numeric literal types work in a similar way, allowing you to specify exact numeric values as types.
let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 3; // This is valid
// diceRoll = 7; // This is a compile-time error
Boolean literal types can be either true
or false
.
let isOpen: true | false;
isOpen = false; // This is valid
Literal types are commonly used in function parameters to restrict the possible values that can be passed in.
function setAlignment(alignment: 'left' | 'center' | 'right') {
console.log(`Setting alignment to ${alignment}`);
}
setAlignment('center'); // This is valid
// setAlignment('top'); // This is a compile-time error
You can also use literal types for object properties to ensure that the properties have specific values.
type ButtonProps = {
type: 'primary' | 'secondary' | 'tertiary';
disabled: boolean;
};
const button: ButtonProps = {
type: 'primary',
disabled: false
};
Literal types can be used in conditional types to perform different type operations based on the literal value.
type GetResult<T> = T extends 'success' ? { status: 'success'; data: any } : { status: 'error'; message: string };
type SuccessResult = GetResult<'success'>; // { status: 'success'; data: any }
type ErrorResult = GetResult<'error'>; // { status: 'error'; message: string }
When you have a set of predefined options, using literal types is a great way to represent them. For example, in a game, you might have different game modes.
type GameMode = 'singleplayer' | 'multiplayer' | 'coop';
function startGame(mode: GameMode) {
console.log(`Starting game in ${mode} mode`);
}
If you are working with an API that has different endpoints, you can use literal types to select the appropriate endpoint.
type ApiEndpoint = '/users' | '/posts' | '/comments';
function fetchData(endpoint: ApiEndpoint) {
// Fetch data from the specified endpoint
}
Don’t overcomplicate your literal types. Only use them when you have a small, well - defined set of possible values. If you have a large number of values, consider using enums instead.
When you have a complex literal type, use type aliases to make your code more readable.
type Color = 'red' | 'green' | 'blue';
function setColor(color: Color) {
console.log(`Setting color to ${color}`);
}
Since literal types can make your code more restrictive, it’s important to document the possible values clearly, especially in function parameters and object properties.
Literal types in TypeScript are a powerful tool for adding precision to your code. They allow you to define exact values as types, which helps catch errors at compile - time and makes your code more self - documenting. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can effectively use literal types in your TypeScript projects.