Sub topic 9
Practical patterns: event handlers, route parameters, and getters
What this chapter assumes
You have met the building blocks from the earlier chapters. These are template literal types, union expansion, Capitalize and the other case helpers, infer inside template patterns, and mapped types with as clauses. This chapter combines them into three patterns you will meet in real code:
- Deriving event handler names and types from an event map.
- Extracting route parameters from a path string.
- Generating getters and setters from an object type.
All three share one shape. You start with a source type, either an object or a string literal. A template literal pattern then transforms or decomposes it into a derived type.
Pattern 1: event handlers
Many libraries name handlers after events. An event called click has a handler called onClick. If you maintain both lists by hand, they drift apart. Instead, write the event map once and derive the handlers.
type AppEvents = {
click: { x: number; y: number };
focus: { target: string };
resize: { width: number; height: number };
};
type Handlers<T> = {
[K in keyof T & string as `on${Capitalize<K>}`]: (payload: T[K]) => void;
};
type AppHandlers = Handlers<AppEvents>;
// {
// onClick: (payload: { x: number; y: number }) => void;
// onFocus: (payload: { target: string }) => void;
// onResize: (payload: { width: number; height: number }) => void;
// }
const handlers: Partial<AppHandlers> = {
onClick: (p) => console.log(p.x, p.y),
onFocus: (p) => console.log(p.target),
};The as clause renames each key, and the value side still uses the original key K to look up the payload. That is why onClick receives the click payload. Two details matter here.
First, keyof T & string filters out number and symbol keys. Capitalize only accepts strings, so without the intersection the compiler reports that K does not satisfy the constraint.
Second, the contextual typing works. The parameter p in onClick: (p) => ... is inferred as { x: number; y: number }, so you get autocomplete on the payload without writing annotations.
Going the other way
Sometimes you have the handler name and need the event name. Use infer to strip the prefix and Uncapitalize to restore the original case.
type EventOf<H extends string> = H extends `on${infer E}`
? Uncapitalize<E>
: never;
type Names = EventOf<"onClick" | "onFocus">; // "click" | "focus"
type None = EventOf<"submit">; // neverBecause H is a bare type parameter, the conditional type distributes over the union. Each member is tested separately, and the results are joined.
Keeping runtime and types in agreement
The type system describes a string. Your runtime code still has to build that string. A small helper can link the two, with one assertion at the boundary:
function handlerName<E extends string>(event: E): `on${Capitalize<E>}` {
const name = "on" + event.charAt(0).toUpperCase() + event.slice(1);
return name as `on${Capitalize<E>}`;
}
const name = handlerName("click"); // type: "onClick"The assertion is a promise you make. TypeScript does not check that your string concatenation produces onClick. Keep helpers like this small and test them, because a bug inside one makes every caller's types wrong.
Pattern 2: route parameters
A route such as /users/:id/posts/:postId contains parameter names. You can extract them at the type level, so a function that fills in the route can require exactly the right values.
Here is the extraction type from earlier in the tutorial, followed by the object type built from it:
type ExtractRouteParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractRouteParams<`/${Rest}`>
: T extends `${string}:${infer Param}`
? Param
: never;
type RouteParams<T extends string> = {
[K in ExtractRouteParams<T>]: string;
};
function buildPath<T extends string>(route: T, params: RouteParams<T>): string {
const values = params as unknown as Record<string, string>;
return route.replace(/:([A-Za-z0-9_]+)/g, (_match: string, name: string) =>
encodeURIComponent(values[name]),
);
}
console.log(buildPath("/users/:id/posts/:postId", { id: "7", postId: "42" }));
// "/users/7/posts/42"The type works in three steps for "/users/:id/posts/:postId":
- The first branch finds the first
:.Paramtakes the text up to the next/, which is"id".Restis everything after that slash:"posts/:postId". - The recursive call runs on
"/posts/:postId". This time no/follows the colon, so the first branch fails and the second branch captures"postId". - The results combine into
"id" | "postId", whichRouteParamsturns into an object type with those two keys.
Inference makes this useful. Because T extends string, a literal argument keeps its literal type. TypeScript then knows exactly which keys params needs:
buildPath("/users/:id", { id: "7" }); // ok
// buildPath("/users/:id", { id: "7", extra: "x" }); // Error: unknown property
// buildPath("/users/:id/posts/:postId", { id: "7" }); // Error: missing postIdWhere route typing breaks down
The type only knows what the pattern tells it. Keep these cases in mind:
| Situation | What the type produces | Why | Column |
|---|---|---|---|
| Route typed as plain `string` | `{}` (no required keys) | `string` matches neither branch, so the result is `never` and the mapped type is empty | |
| `"/users/:id?"` | `"id?"` | The parameter ends at `/` or the end of the string, so the `?` stays in the name | |
| `"/files/:name.json"` | `"name.json"` | Only `/` ends a parameter in this type | |
| `"/a/:x/:y"` | `"x" \ | "y"` | Works: each segment is split on `/` |
The last two rows matter because the runtime regex in buildPath stops at ., while the type does not. When the type and the runtime parser disagree, the compiler approves calls that fail at runtime. Choose one rule, such as "parameters occupy a whole segment", and make both sides follow it.
Pattern 3: getters and setters
Remapping keys with get and set prefixes produces accessor-style interfaces.
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type Setters<T> = {
[K in keyof T & string as `set${Capitalize<K>}`]: (value: T[K]) => void;
};
type Accessors<T> = Getters<T> & Setters<T>;
type Person = { name: string; age: number };
type PersonAccessors = Accessors<Person>;
// {
// getName: () => string;
// getAge: () => number;
// setName: (value: string) => void;
// setAge: (value: number) => void;
// }Intersecting the two mapped types gives one object type that carries both sets of members. You can also generate the runtime object and give it the derived type:
function makeGetters<T extends Record<string, unknown>>(source: T): Getters<T> {
const result: Record<string, () => unknown> = {};
for (const key of Object.keys(source)) {
const name = `get${key.charAt(0).toUpperCase()}${key.slice(1)}`;
result[name] = () => source[key];
}
return result as unknown as Getters<T>;
}
const person = { name: "Ada", age: 36 };
const getters = makeGetters(person);
const n: string = getters.getName();
const a: number = getters.getAge();Each getter returns the right type, string for getName and number for getAge. The cast in the last line of makeGetters is needed because TypeScript cannot see that the loop fills in exactly the keys Getters<T> describes. As with handlerName, the cast is a promise.
Filtering keys while you rename
An as clause that resolves to never removes the key. This lets one mapped type both rename and filter. For example, you can build getters only for string-valued properties:
type StringGetters<T> = {
[K in keyof T & string as T[K] extends string
? `get${Capitalize<K>}`
: never]: () => T[K];
};
type PersonStringGetters = StringGetters<{ name: string; age: number }>;
// { getName: () => string }The age key maps to never, so it does not appear in the result.
Combining the patterns
A typed event emitter uses the same ideas together. The event map is the single source of truth. The emitter's method signatures and the handler names both derive from it.
type UserEvents = {
login: { userId: string };
logout: { userId: string; reason: string };
};
type HandlerMap<T> = {
[K in keyof T & string as `on${Capitalize<K>}`]?: (payload: T[K]) => void;
};
function dispatch<T, K extends keyof T & string>(
handlers: HandlerMap<T>,
event: K,
payload: T[K],
): void {
const key = `on${event.charAt(0).toUpperCase()}${event.slice(1)}`;
const handler = (handlers as Record<string, ((p: T[K]) => void) | undefined>)[key];
handler?.(payload);
}
const handlers: HandlerMap<UserEvents> = {
onLogin: (p) => console.log(`${p.userId} logged in`),
};
dispatch<UserEvents, "login">(handlers, "login", { userId: "u1" });The ? after the mapped key makes each handler optional, so you only implement the events you care about. The explicit type arguments in the call are needed because T appears only inside the mapped type, and TypeScript cannot reliably infer it back from HandlerMap<T>.
Common errors
- Forgetting
& string.keyof Tcan includenumberandsymbol.Capitalize<K>then fails with a constraint error. Intersect withstringfirst. - Using the wrong variable on the value side. After
as, the key is renamed, butKstill refers to the original key. WriteT[K], notT[get${K}]. - Expecting runtime behavior from types. Template literal types disappear at compile time. You must write the matching string code yourself, and a mismatch is invisible to the compiler.
- Losing literals. A route stored in a
letor typed asstringproduces no parameter checks. Keep literals literal. - Recursion on long strings. The route type recurses once per parameter, which is fine. A type that recurses once per character hits depth limits quickly. The next chapter covers that.
Choosing a pattern
Use handler derivation when two lists must stay in sync and one is a mechanical transform of the other. Use route extraction when a string you already write carries structure that functions consume. Use accessor generation when an interface repeats the same shape per property.
Skip these patterns when the derived type would be read by few people and changes rarely. A hand-written type is easier to debug than a three-level mapped type. Error messages from template literal types can be long, so measure the benefit against the cost.
Exercise
What type does ExtractRouteParams produce for the string "/a/:b/c/:d"? Trace the two steps that produce it.
Show answer
"b" | "d". The first branch matches ":b/" with Param "b" and Rest "c/:d", then recurses on "/c/:d". That call fails the first branch because no "/" follows ":d", so the second branch returns "d". The union is "b" | "d".
Exercise
A caller writes const route: string = "/users/:id"; and then calls buildPath(route, {}). Does the compiler report an error? Explain why.
Show answer
No error. T is inferred as string, ExtractRouteParams<string> is never, and RouteParams<string> is an empty object type. The call type-checks, and at runtime values["id"] is undefined, so encodeURIComponent turns it into the text "undefined". Using a const declaration without the string annotation, or as const, keeps the literal and restores the check.
Exercise
What does EventOf<"onClick" | "on"> evaluate to, using the EventOf type from this chapter?
Show answer
"click" | "". The conditional type distributes over the union. "onClick" gives E = "Click", and Uncapitalize turns it into "click". The string "on" also matches the pattern on followed by infer E, with E as the empty string, and Uncapitalize of an empty string is an empty string.
Exercise
Write a mapped type PrefixKeys<T, P extends string> that renames every string key K of T to the prefix P followed by Capitalize<K>, keeping the value types. What must the key clause include so that Capitalize accepts K?
Show answer
Use [K in keyof T & string as ${P}${Capitalize<K>}]: T[K] inside the mapped type braces. The key clause must intersect keyof T with string, because keyof T may include number and symbol keys, and Capitalize only accepts string types.