Sub topic 9
Template literal types for string keys
This chapter assumes you know basic TypeScript types, generics with extends constraints, and mapped types with keyof. You should also be comfortable with as clauses in mapped types, since the examples use them.
A template literal type builds a string type from other types, using the same backtick syntax as JavaScript template strings. The placeholders hold types, not values. When you combine literal types, TypeScript produces every combination.
type Direction = "top" | "bottom";
type Edge = `margin-${Direction}`;
// "margin-top" | "margin-bottom"
type Size = "small" | "large";
type ClassName = `btn-${Size}`;
// "btn-small" | "btn-large"When a placeholder is a union, the result is the union of all combinations. A union of 3 values in one slot and 4 in another produces 12 members, so keep that count in mind for large unions.
Matching string patterns with `${string}`
A placeholder can also be string. This accepts any string that starts or ends with the fixed text.
type DataAttr = `data-${string}`;
const ok: DataAttr = "data-id"; // allowed
// const bad: DataAttr = "id"; // error: does not start with "data-"This pattern works well for prefixes in APIs, such as HTML data attributes or event names.
Built-in string manipulation types
TypeScript provides four intrinsic types for changing the case of a string literal: Uppercase, Lowercase, Capitalize, and Uncapitalize. They distribute over unions, so each member is converted.
type Shout<S extends string> = Uppercase<`${S}!`>;
type Greeting = Shout<"hi" | "bye">;
// "HI!" | "BYE!"Building names from the keys of a type
The most useful combination is a mapped type with an as clause that builds a new name from each key. The key K is string | number | symbol in general, so Capitalize needs string & K to satisfy its constraint.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type User = { id: number; name: string };
type UserGetters = Getters<User>;
// { getId: () => number; getName: () => string }The as clause renames each key, and T[K] keeps the original value type. The same pattern produces the event handler names used in UI frameworks.
flowchart LR
A["Source keys: id, name"] --> B["as clause builds get + Capitalize"]
B --> C["Renamed keys: getId, getName"]
A --> D["T[K] keeps value types"]
D --> CChecking the result
Template literal types also restrict function arguments. A parameter typed as a template literal type accepts only the strings that match the pattern.
type Direction = "top" | "bottom";
type Edge = `margin-${Direction}`;
function setMargin(edge: Edge, value: number): void {
console.log(`${edge}: ${value}px`);
}
setMargin("margin-top", 4); // allowed
// setMargin("margin-left", 4); // error: "margin-left" is not assignableThe error catches misspelled or unsupported names at compile time, before the code runs.
Exercise
Exercise
What is the type of Handlers below?
type Field = "email" | "age";
type Handlers = {
[K in Field as on${Capitalize<K>}Change]: () => void;
};
Show answer
{ onEmailChange: () => void; onAgeChange: () => void }