Skip to content

Checkpoint: Titled Event Listeners

The Course
•
25 min study

Combine today's transformations from memory, on a case the lessons did not show. The event map has three events: added (title), renamed (id and title) and removed (id). Only events whose payload has a title get a listener. Derive that listener object with remapped keys (onAdded, onRenamed), each callback receiving its own event's payload, and derive the matching union of event names back from the map.

Key Remapping's Hooks filtered keys by their name (string or not). Here the as clause must decide by each key's payload type, and a second derived type must find the same events without remapping anything. Day 4 handles dispatching a union event to these callbacks.

Spend twenty-five minutes on the two derived types, the positive calls and the negative compiler experiments.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run.

Predict, then runTypeScript
type Name = Capitalize<"removed">;

const name: Name = "Removed";

console.log(`on${name}`);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
onRemoved

Capitalize changes a string literal type, and the type annotation checks that "Removed" is exactly that result. The runtime template string builds the matching text separately; types never build values.

Acceptance cases before you code

Write a small test plan before implementing. Predict each result, then try it.

Case to tryWhat your result should demonstrate
listeners.onRenamed({ id: "b1", title: "Generics" })Prints Renamed b1 to Generics: the callback sees both fields
Add an onRemoved listenerRejected: removed has no title, so the derived type has no such key
Omit onRenamedRejected: every titled event needs a listener
Put "removed" in a list of titled event namesRejected by the derived name union

After the core task passes, deliberately break one rule and identify the case that notices it. If a case requires a concept you have not recalled, revisit Key Remapping or Typed Registries before opening the solution.

Build it yourself

Exercise

Checkpoint: Titled Event Listeners: practice

Write TitleListeners<E>: for each event whose payload has a title: string, an on… key with a capitalized name and a callback from that payload to string; other events get no key. Write TitledEvent<E>, the union of event names whose payload has a title. Build a listener object checked against TitleListeners<Events> and a TitledEvent<Events>[] list. Print Added Types, Renamed b1 to Generics and added,renamed.

Your workspaceTypeScript
type Events = {
  added: { title: string };
  renamed: { id: string; title: string };
  removed: { id: string };
};

// Derive TitleListeners<E> and TitledEvent<E>, then build and use them.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

An as clause can contain any conditional type, and returning never drops the key. So the condition can ask about E[K], the payload, instead of about K. For the name union, map each key to itself or to never, then collect the property types into one union.

Hint 2: a first step

Write the condition first: does E[K] extend { title: string }? Use it once in the listener type's as clause and once in the value position of a second mapped type. Registries showed how indexing a mapped type with [keyof E] turns its values into a union.

Show one solution
One possible solutionTypeScript
type Events = {
  added: { title: string };
  renamed: { id: string; title: string };
  removed: { id: string };
};

type TitleListeners<E> = {
  [K in keyof E & string as E[K] extends { title: string }
    ? `on${Capitalize<K>}`
    : never]: (payload: E[K]) => string;
};

type TitledEvent<E> = {
  [K in keyof E]: E[K] extends { title: string } ? K : never;
}[keyof E];

const listeners = {
  onAdded: payload => `Added ${payload.title}`,
  onRenamed: payload => `Renamed ${payload.id} to ${payload.title}`
} satisfies TitleListeners<Events>;

const titled: TitledEvent<Events>[] = ["added", "renamed"];

console.log(listeners.onAdded({ title: "Types" }));
console.log(listeners.onRenamed({ id: "b1", title: "Generics" }));
console.log(titled.join(","));

Enable JavaScript to edit and type-check this example.

Text
Added Types
Renamed b1 to Generics
added,renamed

The two types ask the same question, E[K] extends { title: string }, in different places. In TitleListeners the question sits in the as clause, so its answer decides whether the key exists and what it is called, while E[K] in the value still gives each callback its own payload. That is why payload.id is available in onRenamed. In TitledEvent the question sits in the value, so each key maps to itself or never, and [keyof E] collects the survivors into "added" | "renamed"; never members vanish from a union.

The negative cases fail with different diagnostics. An onRemoved listener gives TS2353 'onRemoved' does not exist in type 'TitleListeners<Events>', and omitting onRenamed gives TS1360 "Property 'onRenamed' is missing". Putting "removed" in the list gives TS2322. If you filter on the key instead, with as K extends string ? ... as Hooks did, removed gets a listener again and the object fails with "Property 'onRemoved' is missing".

Change it and test it

Add a fourth event, archived: { id: string; title: string; reason: string }, and predict which listener becomes required and how TitledEvent<Events> changes before you check. Then pass { id: "b1" } to onRenamed at a call site. Write down the distinct diagnostic in each case. Restore a clean check before continuing.

Was this article helpful?

Your response is saved on this device.