Sub topic 13
Putting it together: typed getters and event maps
This chapter combines the pieces from earlier chapters into two helpers you will see in real codebases: a typed getter generator and a typed event system. Each helper uses key remapping, template literal types, conditional types and indexed access together.
What this chapter assumes
You should already be comfortable with these ideas:
keyof Tand indexed accessT[K]- Mapped types, including the
asclause - Conditional types with
extendsandinfer - Template literal types and
Capitalize
If any of these feel shaky, revisit the earlier chapters first. This chapter adds no new syntax. It shows how the existing pieces fit together.
The recipe
Most helpers of this kind follow the same four steps:
- Iterate over the keys of a source type with a mapped type.
- Decide which keys survive, using a conditional type inside
asthat maps unwanted keys tonever. - Build the new key name with a template literal type.
- Derive the new value type from
T[K], often with a conditional type orinfer.
Typed getters
This definition is the one from the earlier chapter on key remapping:
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 }string & K narrows the key to its string part. Capitalize only accepts a string, and keyof T can also contain number and symbol keys. Those keys become never after the intersection, so they are dropped from the result.
A type is only useful if a runtime value matches it. This function builds the getters:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
function makeGetters<T extends object>(source: T): Getters<T> {
const result: Record<string, () => unknown> = {};
for (const key of Object.keys(source) as (keyof T & string)[]) {
const name = `get${key.charAt(0).toUpperCase()}${key.slice(1)}`;
result[name] = () => source[key];
}
return result as unknown as Getters<T>;
}
const user = makeGetters({ id: 1, name: "Ada" });
const id: number = user.getId();
const name: string = user.getName();
console.log(id, name);
// user.getEmail(); // error: Property 'getEmail' does not existThe compiler cannot prove that a loop produces a deferred mapped type, so the function needs the as unknown as Getters<T> cast. This is a common trade-off. The implementation takes one unchecked cast, and every caller gets a precise type. Keep that cast in one small, well-tested function.
Filtering with a conditional type
An object with methods should not get a getter for each method. A conditional type inside as can drop those keys:
type DataGetters<T> = {
[K in keyof T & string as T[K] extends (...args: any[]) => any
? never
: `get${Capitalize<K>}`]: () => T[K];
};
type Model = {
id: number;
name: string;
save(): void;
};
type ModelGetters = DataGetters<Model>;
// { getId: () => number; getName: () => string }The as clause is evaluated once per key. For save, the check T[K] extends (...args: any[]) => any is true, so the key maps to never and the property disappears.
Reversing a getter type with infer
You can also go the other way and recover the value types from a getter type. This uses infer in a mapped type:
type GetterValues<G> = {
[K in keyof G]: G[K] extends () => infer R ? R : never;
};
type Values = GetterValues<{ getId: () => number; getName: () => string }>;
// { getId: number; getName: string }Here the mapped type is homomorphic (it iterates keyof G) and the conditional type is evaluated on each property. These two features are the basis of many other helpers.
Typed event maps
Event systems are a natural fit for these tools. You describe the events once, as an object type that maps each event name to its payload type. Everything else is derived from it.
The ChangeHandlers type from the earlier chapter builds one handler per property:
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.toFixed(0)),
};
handlers.onEmailChange("[email protected]");
handlers.onAgeChange(36);The parameter value is contextually typed. In onEmailChange it is a string, and in onAgeChange it is a number. If you add a field to Form, the compiler reports every object annotated with ChangeHandlers<Form> that is missing the new handler.
A typed emitter
For a runtime event emitter, you rarely need a mapped type in the class itself. A generic constraint on keyof E gives you the correlation between event name and payload:
class Emitter<E extends object> {
// Internal storage is loosely typed on purpose. The public API is not.
private listeners = new Map<keyof E, Array<(payload: any) => void>>();
on<K extends keyof E>(event: K, listener: (payload: E[K]) => void): void {
const list = this.listeners.get(event) ?? [];
list.push(listener);
this.listeners.set(event, list);
}
emit<K extends keyof E>(event: K, payload: E[K]): void {
for (const listener of this.listeners.get(event) ?? []) {
listener(payload);
}
}
}
type AppEvents = {
login: { user: string };
logout: { reason: string };
tick: number;
};
const bus = new Emitter<AppEvents>();
bus.on("login", (payload) => console.log(payload.user));
bus.emit("login", { user: "ada" });
bus.emit("tick", 1);
// bus.emit("tick", "one"); // error: string is not assignable to number
// bus.emit("signup", {}); // error: "signup" is not in keyof AppEventsThe type parameter K links the two arguments. Once K is inferred as "login", the payload type is E["login"], which is { user: string }.
Deriving a subscription API
A mapped type can turn the same event map into named subscription methods, in the style onLogin(listener):
type Subscribers<E> = {
[K in keyof E & string as `on${Capitalize<K>}`]: (
listener: (payload: E[K]) => void,
) => void;
};
type AppSubscribers = Subscribers<{
login: { user: string };
tick: number;
}>;
// {
// onLogin: (listener: (payload: { user: string }) => void) => void;
// onTick: (listener: (payload: number) => void) => void;
// }Because both Emitter and Subscribers read from the same AppEvents type, adding an event in one place updates the whole API.
Edge cases and common errors
Optional properties stay optional
A mapped type of the form [K in keyof T as ...] is still homomorphic, so it copies the readonly and ? modifiers from the source:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type Profile = { id: number; nickname?: string };
type ProfileGetters = Getters<Profile>;
// { getId: () => number; getNickname?: () => string | undefined }getNickname is itself optional, so callers must check it before calling. If you want every getter to exist, add -? after the closing bracket: [K in keyof T as ...]-?: () => T[K]. The return type still includes undefined, because the property can be missing from the source.
Non-string keys vanish
keyof T & string removes number and symbol keys. For { 0: "a"; name: string }, no getter is produced for key 0. This is usually what you want, but it can be a surprise. Template literal types do accept numbers, so ${K & (string | number)} keeps numeric keys. Note that Capitalize still needs a string, so wrap the pieces carefully.
Name collisions
Two source keys can map to the same new name. For example, id and Id both become getId. TypeScript does not report an error. The properties merge, and the value type becomes a union of their value types. If collisions are possible in your data, test the type with an example that has colliding keys.
Interfaces and index signatures
If you constrain a type parameter with E extends Record<string, unknown>, an interface is rejected, because interfaces have no implicit index signature. A type alias is accepted. The constraint E extends object used in Emitter accepts both.
Distribution and `never`
If the type parameter in a conditional is a union, the check distributes over it. A getter helper that wraps a conditional around T itself, as opposed to around T[K], may return a union of getter types. When T is never, a distributive conditional returns never. Wrap both sides in a tuple ([T] extends [never]) when you need to detect never explicitly.
Choosing between approaches
| Goal | Tool | Example |
|---|---|---|
| Rename every key | Mapped type with `as` and a template literal | `Getters<T>` |
| Drop some keys | `as` clause returning `never` | `DataGetters<T>` |
| Change value types | Conditional type on `T[K]` | `GetterValues<G>` |
| Tie two arguments together | Generic parameter `K extends keyof E` | `Emitter.emit` |
| Preserve optional and readonly | Keep the `keyof T` form | all of the above |
Exercise
Write a type Setters<T> that maps each property of T to a method named set plus the capitalized key, taking one argument of the property type and returning void. For { id: number; name: string } the result should be { setId: (value: number) => void; setName: (value: string) => void }. Then change it so readonly properties of T are not given a setter.
Show answer
type Setters<T> = { [K in keyof T & string as set${Capitalize<K>}]: (value: T[K]) => void; };
The version that skips readonly properties needs a helper that detects readonly keys, for example by comparing { [P in K]: T[K] } against { -readonly [P in K]: T[K] } with a mutual-assignability check inside as. TypeScript treats readonly and mutable properties as mutually assignable, so this check does not work. The practical answer is that readonly cannot be detected reliably with assignability. Instead, take the keys to exclude as a second type parameter: type Setters<T, Skip extends keyof T = never> = { [K in keyof T & string as K extends Skip ? never : set${Capitalize<K>}]: (value: T[K]) => void; };
Exercise
Given type AppEvents = { login: { user: string }; tick: number }, what is the type of payload in bus.on("tick", (payload) => ...) for an Emitter<AppEvents>, and why does bus.emit("tick", "one") fail?
Show answer
payload is number. Calling on("tick", ...) infers K as "tick", so the listener parameter has type E["tick"], which is number. In emit("tick", "one"), K is also inferred as "tick", so the second argument must be number. The string "one" is not assignable to it, and the compiler reports an error.
Exercise
What does DataGetters<{ id: number; save(): void; label?: string }> produce?
Show answer
It produces { getId: () => number; getLabel?: () => string | undefined }. The key save maps to never because its value type extends a function type, so it is dropped. The key label keeps its optional modifier, so getLabel is optional and its return type includes undefined.