Sub topic 9
Practical Patterns: Event Handlers, Route Parameters, and Getters
Prerequisites
This chapter assumes that you know basic TypeScript types, string literal unions, generics, conditional types, and mapped types. You should also understand that a type describes valid programs but does not change JavaScript behavior at runtime.
Template literal types become useful when names follow a predictable string pattern. They can connect related names so that changing one type automatically updates the others.
Event handler names
Suppose an API accepts event names such as "click" and "focus", but its handler properties must be named onClick and onFocus. A template literal type can build those names:
type EventName<T extends string> = `on${Capitalize<T>}`;
type EventHandlers<T extends string> = {
[E in T as EventName<E>]: (event: Event) => void;
};
type UIHandlers = EventHandlers<"click" | "focus">;
const handlers: UIHandlers = {
onClick: event => console.log(event.type),
onFocus: event => console.log(event.type),
};Capitalize<T> changes the first character of each string in T. Since T is a union, the transformation distributes over every member. EventHandlers<"click" | "focus"> therefore produces an object with both required properties.
The as clause remaps each original union member into a new property key. The value type remains a function that receives an Event.
Route parameters
Routes often contain named parameters:
/users/:id/posts/:postIdThe route itself is a string, but the application usually needs an object containing the extracted values. Conditional types and infer can find the parameter names.
type ExtractRouteParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractRouteParams<`/${Rest}`>
: T extends `${string}:${infer Param}`
? Param
: never;
type RouteParams<Path extends string> = {
[P in ExtractRouteParams<Path>]: string;
};
type PostParams = RouteParams<"/users/:id/posts/:postId">;
// { id: string; postId: string }
function loadPost(
path: "/users/:id/posts/:postId",
params: PostParams,
): string {
return `${path}: ${params.id}/${params.postId}`;
}
loadPost("/users/:id/posts/:postId", {
id: "u1",
postId: "p9",
});The first conditional pattern captures the text after a colon and before the next slash. It then calls itself with the remaining route. The second pattern handles the final parameter. If no parameter exists, the result is never.
The mapped type converts the resulting union, "id" | "postId", into object keys. This approach checks parameter names at compile time, but it does not validate the values at runtime. If values must be numbers or UUIDs, the function still needs runtime validation.
Getters from object keys
Template literal types can also create related method names from an existing object type:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type Person = {
name: string;
age: number;
};
type PersonGetters = Getters<Person>;
const personGetters: PersonGetters = {
getName: () => "Ada",
getAge: () => 36,
};keyof T produces the keys of T. The & string constraint keeps only keys that can be used as string template parts. The as clause changes name into getName and age into getAge. Each getter still returns the value type from its original property.
This pattern is useful for generated APIs, stores, and adapters. It is safest when the runtime object is generated by the same convention. A type cannot create the methods for you.
Choosing a pattern
| Pattern | Input | Generated result | Common use |
|---|---|---|---|
| Event names | String union | `on${Capitalize<Name>}` | Handler objects |
| Route parameters | Route string | Parameter-name union or object | Typed navigation |
| Key remapping | Object keys | New method names | Getters and adapters |
How the pieces connect
Exercise
Exercise
What type does Getters<{ title: string; count: number }> produce?
Show answer
It produces { getTitle: () => string; getCount: () => number }.