Add a renamed event with a validated id and nonblank title in a local copy. The type map should make a new channel required. The exhaustive switch should require a dispatch branch. Neither mechanism automatically writes the decoder: add an unknown-data branch that validates and projects the new payload.
Keep the same contract around callback returns, duplicate subscriptions, snapshot behavior and disposal. A new event should not silently change the lifetime rules of every existing port. Test a valid renamed message, a blank title, extra-field removal and the actual subscriber payload.
Add a positive public consumer and a focused negative caller missing title. Then run the declaration-consumer checks and runtime suite. A clean mapped registry alone cannot prove the new parser accepts the intended wire data.
What needs Node: the full extension is done in the downloaded project, with Node.js 22+. The guided path and the reference changes below are on this page, so you can follow them, or compare against them, even without running it. The browser exercise rehearses coverage on a small formatter registry.
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.
type Events = {
added: { title: string };
renamed: { title: string };
};
type Labels<E> = { [K in keyof E]: (payload: E[K]) => string };
const labels = {
added: book => `Added ${book.title}`,
renamed: book => `Renamed ${book.title}`
} satisfies Labels<Events>;
console.log(labels.renamed({ title: "Types" }));Enable JavaScript to edit and type-check this example.
Check your prediction
Renamed TypesAdd a vocabulary branch and its runtime evidence together
Adding renamed to EventMap demands channel coverage and an exhaustive dispatch branch. It does not instantiate a port, decode wire data or choose normalization rules. Write one accepted raw record and several rejected records before editing the type map.
Reuse checked id construction and preserve the existing lifetime policy. A new event must not accidentally permit asynchronous listeners or change how disposal and callback failure behave for every old event.
| Boundary or case | What to inspect |
|---|---|
| Map and channels | Require exactly the renamed payload contract |
| Decoder and dispatch | Validate the raw branch and route a correlated payload |
| Consumer and runtime | Reject missing title and verify actual normalized subscriber data |
Follow coverage errors, then add invalid runtime fixtures the checker cannot inspect. Re-run existing snapshot, cleanup and failure tests after the new happy path works. Explain which file owns each guarantee instead of copying the branch blindly.
A guided path for renamed
Work in this order. Each step tells you what the compiler will and will not point you to.
- Add the type. In domain.ts, add
renamedtoEventMapwith a readonlyid: BookIdand readonlytitle: string. Runnpm run check. Expect exactly two errors, both in gateway.ts: TS1360 saysProperty 'renamed' is missingfrom the channels object, and TS2345 says the renamed eventis not assignable to parameter of type 'never'atunreachable(event). That second one is the exhaustive switch doing its job. - Satisfy the gateway. Add a renamed channel, a
case "renamed"branch and a dispose call. The check now passes, yet no renamed message can arrive: the decoder still answers "Unknown event type". Nothing in the types told you this. - Write failing tests first. In gateway.test.mjs, add a test that sends a valid renamed record with padding and an extra field, plus a blank title and a missing title. Run
npm testand watch the valid case fail. - Teach the decoder. Renamed has the same payload rules as added, so the added branch can accept both types and copy
value.typeinto the result. - Update the consumer. consumer.ts has
@ts-expect-error declared public channels have no renamed key. That directive is now unused (TS2578), which is correct: the public surface changed on purpose. Replace it with a focused negative caller for a renamed event without a title.
Build it yourself
Extending Event Contracts: practice
Create a formatter registry covering added, removed and renamed payloads. Added and renamed use title; removed uses id. Print Renamed Types and Removed b1. Use satisfies to require every key.
// 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
The new key should be required by the mapped contract, not manually asserted as present.
Hint 2: a first step
Add renamed to the event map before constructing the complete registry.
Show one solution
type Events = {
added: { title: string };
removed: { id: string };
renamed: { title: string };
};
type Labels<E> = { [K in keyof E]: (payload: E[K]) => string };
const labels = {
added: book => `Added ${book.title}`,
removed: book => `Removed ${book.id}`,
renamed: book => `Renamed ${book.title}`
} satisfies Labels<Events>;
console.log(labels.renamed({ title: "Types" }));
console.log(labels.removed({ id: "b1" }));Enable JavaScript to edit and type-check this example.
Renamed Types
Removed b1Adding renamed to Events makes satisfies Labels<Events> require a renamed formatter. Without it, the check fails with TS1360 "Property 'renamed' is missing". The formatter gets a title payload from the map without an annotation. This is the registry half of the extension; the guided path above adds the decoder branch and tests, which no mapped type can require.
Reference changes
Compare after your own attempt. These changes pass npm test with seven test groups.
domain.ts, the map and the shared branch:
removed: { readonly id: BookId };
renamed: {
readonly id: BookId;
readonly title: string;
};
}; if (value.type === "added" || value.type === "renamed") {
// ... the existing title validation, unchanged ...
return {
ok: true,
value: {
type: value.type,
payload: { id: id.value, title: payload.title.trim() }
}
};
}gateway.ts, three additions:
renamed: createChannel<EventMap["renamed"]>() case "renamed":
return channels.renamed.publish(event.payload); channels.renamed.dispose();consumer.ts, the directive that replaces the old "no renamed key" one:
if (id.ok) {
// @ts-expect-error the renamed payload requires a title
const unnamed: AppEvent = { type: "renamed", payload: { id: id.value } };
}gateway.test.mjs, the new runtime group:
test("renamed events are validated, normalized and dispatched", () => {
const gateway = createGateway();
const titles = [];
gateway.channels.renamed.subscribe(book => {
titles.push(book.title);
});
assert.deepEqual(
gateway.receive({
type: "renamed",
payload: { id: " b1 ", title: " Types 2 ", extra: 1 }
}),
{ ok: true, value: true }
);
assert.equal(
gateway.receive({ type: "renamed", payload: { id: "b1", title: " " } }).ok,
false
);
assert.equal(
gateway.receive({ type: "renamed", payload: { id: "b1" } }).ok,
false
);
assert.deepEqual(titles, ["Types 2"]);
});type: value.type works because the if has already narrowed value.type to "added" | "renamed", and both branches have the same payload shape. If renamed later needs different rules, split the branch rather than adding conditions inside it.
Change it and test it
In the local project, list the expected compiler failures immediately after adding the map key. Then add decoder behavior and prove malformed renamed data never reaches its subscriber.
Completion is saved in this browser only. It does not measure mastery.