Skip to content

Typed Registries

The Course
•
20 min study

A registry is an object whose keys identify operations. A mapped contract can connect every key to its particular input type: Formatters<T> requires one formatter for each property in T, with that property's own value type.

Using satisfies on an explicit object checks that coverage and contextually types the callbacks. The title callback receives string while pages receives number. A broad (value: string | number) => string everywhere would lose that useful relationship.

Types describe coverage, but runtime code still supplies every implementation. This course deliberately builds small explicit registries rather than casting the output of Object.keys into a generic mapped type. Object.keys returns runtime strings and does not prove every required function was constructed.

When an event type is added, a complete registry should fail checking until its implementation exists. That maintenance signal is valuable only if you do not silence it with a broad assertion. The final gateway uses the same idea for its channels.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
type Formatters<T> = { [K in keyof T]: (value: T[K]) => string };

type Book = {
  title: string;

  pages: number;
};

const format = {
  title: text => text.trim(),
  pages: count => `${count} pages`
} satisfies Formatters<Book>;

console.log(format.title(" Types "));
console.log(format.pages(120));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types
120 pages

Read the compiler error

Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.

Find and fix the type errorTypeScript
type Formatters<T> = { [K in keyof T]: (value: T[K]) => string };

const format = { pages: (count: string) => count } satisfies Formatters<{
  pages: number;
}>;

console.log(format);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The message has three lines; read the last one first: Type 'number' is not assignable to type 'string'. The middle line, Types of parameters 'count' and 'value' are incompatible, says the mismatch is in a callback parameter: the registry will pass a number to a function that only accepts a string.

The pages callback must accept number. A registry is not safe merely because its keys are present.

Coverage and payload compatibility are separate checks

A mapped registry has two responsibilities: every required key exists, and each implementation accepts the payload associated with its key. A broad function union can lose the second relationship even while all names appear to be present.

Construct a small literal satisfying the derived contract and inspect the callback parameter types. Context lets implementations remain concise without sacrificing their specific input shapes. The runtime object still has to be written or generated by real code; a mapped alias cannot manufacture it.

Coverage and payload compatibility are separate checks: traceTypeScript
type Fields = {
  title: string;

  pages: number;
};

type Formatters<T> = { [K in keyof T]: (value: T[K]) => string };

const format = {
  title: value => value.trim(),
  pages: value => `${value} pages`
} satisfies Formatters<Fields>;

console.log(format.title(" Types "));
console.log(format.pages(0));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types
0 pages

Each callback receives a different type. The pages formatter can use zero as meaningful data without a truthiness fallback.

Coverage and payload compatibility are separate checks: contrastTypeScript
type Events = {
  added: { title: string };

  removed: { id: string };
};

type Formatters<E> = { [K in keyof E]: (value: E[K]) => string };

const format = {
  added: value => value.title,
  removed: value => value.id
} satisfies Formatters<Events>;

console.log(Object.keys(format).join(","));
console.log(format.removed({ id: "b1" }));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
added,removed
b1

The explicit registry implements both derived requirements. Adding a key to Events will demand another implementation; it will not add one to this runtime object automatically.

One call for every event: the correlated-union problem

The registry has one formatter per event type. The obvious next step is a single function that formats any event by looking up its formatter: format[event.type](event.payload). It does not compile, and the reason is the most important limitation of this week.

Find and fix the type error: one call for every eventTypeScript
type Events = { added: { title: string }; removed: { id: string } };
type Formatters<E> = { [K in keyof E]: (value: E[K]) => string };
type AppEvent = { [K in keyof Events]: { type: K; payload: Events[K] } }[keyof Events];

const format = {
  added: value => value.title,
  removed: value => value.id
} satisfies Formatters<Events>;

function describe(event: AppEvent): string {
  return format[event.type](event.payload);
}

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is the first: TS2345: Argument of type '{ title: string; } | { id: string; }' is not assignable to parameter of type '{ title: string; } & { id: string; }'. Read both sides. The checker typed format[event.type] as "the added formatter or the removed formatter", and the only argument safe for either is one that is both payloads: the intersection on the right. It typed event.payload independently as "either payload": the union on the left. It has forgotten that the type and payload came from the same event. That lost link is what "correlated union" means.

This is where as never tempts: format[event.type](event.payload as never) compiles, and would also compile if you passed the wrong payload. Don't. Use one of the two fixes below.

Fix 1 narrows the event first, so each branch has one known type and one known payload. Fix 2 (TypeScript 4.6 and later) makes the link explicit with a type parameter: for a single K, format[K] accepts exactly Events[K]. It works when the registry's type is written as the mapped type, Formatters<Events>, and the event's type is EventOf<K>.

Two ways to keep type and payload togetherTypeScript
type Events = { added: { title: string }; removed: { id: string } };
type Formatters<E> = { [K in keyof E]: (value: E[K]) => string };
type EventOf<K extends keyof Events> = { type: K; payload: Events[K] };
type AppEvent = { [K in keyof Events]: EventOf<K> }[keyof Events];

const format: Formatters<Events> = {
  added: value => value.title,
  removed: value => value.id
};

function describe<K extends keyof Events>(event: EventOf<K>): string {
  return format[event.type](event.payload);
}

function viaSwitch(event: AppEvent): string {
  switch (event.type) {
    case "added":
      return format.added(event.payload);
    case "removed":
      return format.removed(event.payload);
  }
}

const events: AppEvent[] = [
  { type: "added", payload: { title: "Types" } },
  { type: "removed", payload: { id: "b1" } }
];
for (const event of events) {
  console.log(describe(event), viaSwitch(event));
}

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types Types
b1 b1

The switch scales by one case per event and is the easiest to read; Day 4's dispatch lesson uses it. The generic version scales to any number of events with no new code, at the price of a signature that readers must study. Either way, no assertion is needed.

Try the rule on new inputs

Remove one key and then change one callback input independently. Read the different diagnostics. Keep a positive call for each key so an over-restrictive contract cannot pass a negative-only test suite.

Trace the contract before building

A registry combines stable names with type-specific values. Preserve its concrete key set long enough to derive useful relationships, then check that each entry meets the shared contract. Widening too early can erase the information a later lookup needs.

Trace a known key through the registry to its result type, then consider an arbitrary string from a form. The latter still needs runtime membership evidence before it can be treated as a supported key: a key list and a text is keyof Events guard, as in the intermediate keyof lesson. Test an omitted entry, an incompatible entry, and a real lookup. This separates completeness of the authored registry from validation of external input, which remains an application boundary responsibility.

Build it yourself

Exercise

Typed Registries: practice

Create Formatters for {enabled:boolean;minutes:number}. Format false as Off and 25 as 25 min. Use satisfies, with no explicit callback parameter annotations and no any.

Your workspaceTypeScript
// Start from the stated contract. Add a valid call and an edge case.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Context comes from the mapped contract at the object boundary.

Hint 2: a first step

Keep a formatter under each original key and branch on the boolean input.

Show one solution
One possible solutionTypeScript
type Formatters<T> = { [K in keyof T]: (value: T[K]) => string };

const format = {
  enabled: value => (value ? "On" : "Off"),
  minutes: value => `${value} min`
} satisfies Formatters<{
  enabled: boolean;

  minutes: number;
}>;

console.log(format.enabled(false));
console.log(format.minutes(25));

Enable JavaScript to edit and type-check this example.

Text
Off
25 min

satisfies gives each callback its parameter type from the mapped contract, which is why value ? "On" : "Off" treats value as boolean and ${value} min as number, with no annotations. It also checks coverage: leaving out minutes fails with a missing-property error, and format.enabled("yes") fails as a wrong argument. Those two diagnostics protect different halves of the contract. The strings themselves ("Off", "25 min") are runtime behavior, shown only by running.

Change it and test it

Remove minutes and inspect the missing-property error. Then call the enabled formatter with text and inspect the argument error. These protect different parts of the contract.

Was this article helpful?

Your response is saved on this device.