typescript / intermediate
Snippet
Template Literal Types
Template literal types allow you to create new string types by combining existing union types. This is extremely useful for generating predictable string patterns like CSS classes or action names.
snippet.ts
1
2
3
4
5
6
7
type Direction = "left" | "right";type Speed = "fast" | "slow";type Movement = `${Direction}-${Speed}`;const action: Movement = "left-fast";// const error: Movement = "up-fast"; // Error
Breakdown
1
type Movement = `${Direction}-${Speed}`;
Combines every string in 'Direction' with every string in 'Speed' separated by a hyphen.
2
const action: Movement = "left-fast";
Validates that the string follows one of the four generated permutations.