Sub topic 13
Putting it together: typed getters and event maps
This chapter assumes you know object types, generics, mapped types ([K in keyof T]), conditional types (T extends U ? X : Y), and template literal types. Key remapping with as requires TypeScript 4.1 or later.
Typed getters from an object type
A getter is a function that returns a property's value. Instead of writing one getter type per property by hand, generate them from the object type with a mapped type. The as clause rewrites each key before it becomes a property of the new type, while T[K] keeps the original value type.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type User = { id: number; name: string };
const userGetters: Getters<User> = {
getId: () => 1,
getName: () => "Ada",
};
console.log(userGetters.getName()); // "Ada"Capitalize is a built-in string type that uppercases the first character. The string & K intersection narrows the key to a string, because keyof T can also produce symbol keys, and Capitalize accepts only strings.
Typed event maps
An event map follows the same pattern. Each property in a form becomes a change handler whose parameter type matches the field.
type ChangeHandlers<T> = {
[K in keyof T & string as `on${Capitalize<K>}Change`]: (value: T[K]) => void;
};
type Form = { email: string; age: number };
const handlers: ChangeHandlers<Form> = {
onEmailChange: (value) => console.log(value.toUpperCase()),
onAgeChange: (value) => console.log(value + 1),
};
handlers.onAgeChange(30); // logs 31Because the handler type is contextual, value gets its type from the map. You do not annotate it. If you write onAgeChange: (value: string) => {}, TypeScript reports an error, since the handler must accept a number.
The table shows how each source key maps to an output key and value type:
| Source type | Source key | Output key | Output type |
|---|---|---|---|
| `User` | `name` | `getName` | `() => string` |
| `Form` | `age` | `onAgeChange` | `(value: number) => void` |
How the pieces fit
The mapped type iterates over keys. The as clause computes a new key with a template literal type. The value type comes from indexed access, T[K]. Conditional types can be added to the as clause to drop keys, because mapping a key to never removes that property.
Exercise
Exercise
Given type Form = { email: string; age: number } and ChangeHandlers<Form> from above, what is the type of ChangeHandlers<Form>["onAgeChange"]?
Show answer
It is (value: number) => void. The value type comes from T["age"], which is number.