Template literal types
| `on-${T}` types | |
| Typed event keys | |
| Split strings | |
| Intrinsic Uppercase |
`on-${T}` types
A template literal type builds string types from a pattern. Placeholders like ${T} are filled in when the type is used.
EventName of click is the single string on-click. Any typo in the input produces a wrong event name that the compiler catches.
type EventName<T extends string> = `on-${T}`;
type Click = EventName<"click">; // "on-click"
Typed event keys
Combine templates with keyof to stamp out one listener name per property. Each key of Props gets its own change event.
TitleChange is exactly the string change:title. Rename a property and every listener name follows it.
type Props = {
title: string;
open: boolean;
};
type Listener<K extends keyof Props> = `change:${K}`;
type TitleChange = Listener<"title">; // "change:title"
Split strings
Templates also run backwards with infer to split strings apart. Match the pattern, capture the head and the rest, and return them as a tuple.
P is the pair of a and b-c for the input a-b-c. When nothing matches, the fallback keeps the whole string.
type Split<S extends string> = S extends `${infer H}-${infer Rest}` ? [H, Rest] : [S];
type P = Split<"a-b-c">; // ["a", "b-c"]
Intrinsic Uppercase
TypeScript ships intrinsic helpers that rewrite string casing. Uppercase turns hey into HEY without any runtime code.
Lowercase, Capitalize, and Uncapitalize round out the set. They shine for normalizing keys and event names.
type Shout<T extends string> = Uppercase<T>;
type Loud = Shout<"hey">; // "HEY"
Next: keyof and typeof
Article author: Arthur Isaev