Skip to content

Mapped types and key remapping

Relay routes each event to a handler. The handler table is a Record<string, (event: RelayEvent) => void>. Nothing says that JobFailed has a handler, and a handler for "JobFaild" is accepted. Worse, the JobFailed handler receives the whole RelayEvent union and has to narrow again, although the table already knows which event it gets.

The table has the same shape as the union: one entry per event, and each entry’s type depends on the event. A mapped type builds an object type from a list of keys, and lets each value depend on its key.

A mapped type loops over a union of keys. K is each key in turn, and the right side is the value type:

type Tag = "WebhookReceived" | "JobQueued" | "JobFailed" | "JobSucceeded"
type Seen = { [K in Tag]: number }
// { WebhookReceived: number; JobQueued: number; JobFailed: number; JobSucceeded: number }
const counts: Seen = { WebhookReceived: 0, JobQueued: 0, JobFailed: 0, JobSucceeded: 0 }
// @ts-expect-error: property 'JobSucceeded' is missing
const missing: Seen = { WebhookReceived: 0, JobQueued: 0, JobFailed: 0 }

This is Record<Tag, number>, and Record is built this way (lesson 6). A missing key and a misspelled key are both errors, which the loose Record<string, ...> never reported.

[K in keyof T] loops over the keys of another type. When you write exactly this form, the new type keeps each property’s modifiers (readonly and ?). This is the homomorphic form:

interface Settings {
readonly host: string
readonly port?: number
}
type Copy<T> = { [K in keyof T]: T[K] }
type SettingsCopy = Copy<Settings> // { readonly host: string; readonly port?: number }
type Listeners<T> = { [K in keyof T]?: Set<(value: T[K]) => void> }
type SettingsListeners = Listeners<Settings>

Listeners is the shape from M3’s emitter: { [K in keyof Events]?: Set<Listener<Events[K]>> }. Read it as “for each event name K in Events, an optional set of listeners that take that event’s payload Events[K]”. It is how the emitter stores listeners with no any: the storage shape is derived from the event map. T[K] is indexed access from M3.

A - before a modifier removes it, a + (the default) adds it:

interface Settings {
readonly host: string
readonly port?: number
}
type Mutable<T> = { -readonly [K in keyof T]: T[K] }
type Complete<T> = { [K in keyof T]-?: T[K] }
declare const edit: Mutable<Settings>
edit.host = "0.0.0.0" // allowed: readonly is gone
type Ready = Complete<Settings> // { readonly host: string; readonly port: number }

Complete is useful once defaults have been applied: the config loader accepts a partial config, fills the holes, and returns a type with nothing optional. With exactOptionalPropertyTypes on, -? removes the ? and does not add undefined.

as after the key lets you change the key, or return never to drop it. First, the handler table: each key is the event’s own _tag, and E is the whole union member:

type RelayEvent =
| { readonly _tag: "WebhookReceived"; readonly source: string; readonly body: string }
| { readonly _tag: "JobQueued"; readonly jobId: string; readonly attempt: number }
| { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string }
| { readonly _tag: "JobSucceeded"; readonly jobId: string }
type Handlers = { [E in RelayEvent as E["_tag"]]: (event: E) => void }
const handlers: Handlers = {
WebhookReceived: (event) => console.log(event.source),
JobQueued: (event) => console.log(event.attempt),
JobFailed: (event) => console.log(event.reason),
JobSucceeded: (event) => console.log(event.jobId),
}

Here the loop is over the union’s members, not its keys. Each event is the member for its key, so event.reason exists in JobFailed and nowhere else. Add a JobCancelled event and handlers stops compiling until you handle it.

Second, as can filter. A key that maps to never is dropped:

type DataOnly<T> = { [K in keyof T as T[K] extends (...args: never[]) => unknown ? never : K]: T[K] }
interface Job {
id: string
retries: number
run(): void
}
type JobData = DataOnly<Job> // { id: string; retries: number }

DataOnly is lesson 2’s filter again, applied to keys. This is what you need to log or serialize an object: its data, without its methods. Template literal keys like `on${K}` come in the next lesson.

The runtime side has one catch. handlers[event._tag](event) does not compile: the key and the event are linked, but TypeScript sees a union of functions that each need a different argument. A switch narrows the event in each branch, so each call is checked:

type RelayEvent =
| { readonly _tag: "JobQueued"; readonly jobId: string }
| { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string }
type Handlers = { [E in RelayEvent as E["_tag"]]: (event: E) => void }
function dispatch(handlers: Handlers, event: RelayEvent): void {
// @ts-expect-error: the union of handlers needs an argument that fits every event at once
handlers[event._tag](event)
}
function dispatchChecked(handlers: Handlers, event: RelayEvent): void {
switch (event._tag) {
case "JobQueued":
return handlers.JobQueued(event)
case "JobFailed":
return handlers.JobFailed(event)
}
}

Derive Handlers from RelayEvent, write Mutable, Complete and DataOnly, then implement dispatch and dataOnly. The starter’s Handlers is a loose Record: the tests expect a missing tag, an unknown tag and a wrongly typed handler to be errors.

  • { [K in Keys]: V } builds an object type with one property per key. Missing and extra keys are errors.
  • { [K in keyof T]: ... } is homomorphic: it keeps readonly and ?. -readonly and -? remove them.
  • Looping over a union’s members with as E["_tag"] gives each key a value that depends on its own member. Add an event and the table fails to compile until it is handled.
  • as returning never drops a key. That is how you keep only the data keys.
  • M3’s emitter storage is a mapped type over the event map.
  • TypeScript cannot correlate handlers[event._tag] with event: narrow with a switch.
  • Mapped Types: the as clause and modifiers.
  • TypeScript 4.1: template literal types, key remapping and recursive conditional types.