TypeScript / Intermediate / Lesson 14
Preserve event names and payload relationships
Use a keyed event map and generic functions to keep event payloads aligned with their names while preserving runtime validation.
On this page
Lesson goals
- Model an event name to payload mapping.
- Use indexed access to preserve a key and value relationship.
- Validate external event data before typed delivery.
- Connect event keys to their corresponding payload and handler types.
- Decode unknown messages and test delivery, lifecycle, and authorization boundaries.
Model the relationship
An event channel carries more than a name and an unrelated object: each event name has a particular payload contract. A map from literal names to payload types expresses that relationship in one place. For example, saved carries an id while failed carries a message. Callers can then use the event name to select the corresponding payload rather than relying on comments or unchecked casts.
Connect the key and payload
The generic parameter K is constrained to keys of Events. Indexed access Events[K] selects the payload associated with that key, and Handler<K> accepts the same payload. The deliver function demonstrates the connection without maintaining a registry or asserting its internal storage. This is a teaching boundary: real event systems also need clear ordering, subscription lifetime, and exception handling contracts.
type Events = {
saved: { id: string };
failed: { message: string };
};
type Handler<K extends keyof Events> = (payload: Events[K]) => void;
function deliver<K extends keyof Events>(name: K, payload: Events[K], handler: Handler<K>): void {
handler(payload);
}
The same generic key selects both the payload and handler parameter type.
Use the contract
The saved handler reads id because its declared key selects the saved payload. The matching call supplies that shape; the commented call supplies a failed payload and should produce a type error if uncommented and checked. Put both code blocks in one TypeScript file. A type test should verify the invalid call separately, so an accidental widening of the public contract is visible during development.
const onSaved: Handler<"saved"> = payload => console.log(payload.id);
deliver("saved", { id: "a1" }, onSaved);
// deliver("saved", { message: "offline" }, onSaved); // type error
The active call matches the saved contract; the commented call is intentionally invalid.
Validate outside the type system
A message received from a socket or parsed JSON is not made safe by annotating it as Events. Begin with unknown, check the event name and the associated payload fields, then construct the trusted event before calling typed code. Reject unknown names or handle them according to a documented compatibility policy. Never invoke a handler with a cast merely to bypass an error that reveals an unvalidated boundary.
Test lifecycle and behavior
Test each accepted event with its matching payload and verify that a handler receives it once under the chosen delivery contract. Include a wrong payload and an unknown name in runtime boundary tests, plus a compile-time negative example. If an actual implementation stores handlers, separately test unsubscribe, repeated subscriptions, and a handler that throws. The type relationship alone does not determine these runtime behaviors.
Model the event-to-payload relationship
A keyed event contract starts with a single map from event names to payload types. For example, saved can carry {id: number} and failed can carry {message: string}. A handler for a key K should receive Events[K], so a failed handler reads message while a saved handler reads id. Keeping that relationship in one declaration reduces drift between separate name and payload lists. It does not automatically implement event delivery or validate data from a network.
Choose stable names and define the meaning and required fields of each payload. A type map can express optional fields and distinguish variants, but it does not decide authorization, retry behavior, or lifecycle. An event source, registry, and consumer need an explicit ownership and failure contract. The examples below use synthetic in-process functions with the pinned TypeScript 5.7.3 configuration and Node 22.23.3; they do not connect to an event service.
Preserve the key through the call
A generic signature can connect K extends keyof Events to a payload of Events[K]. When K is the literal "saved", the checker requires the saved payload; when it is "failed", it requires the failed payload. A broad independent union of names paired with an independent union of payloads can lose this relationship and permit mismatched combinations. Test a valid saved pair, a valid failed pair, and a mismatched payload as a negative type case.
Inference depends on how the key and payload are represented. Avoid claiming that an arbitrary untrusted string becomes a safe key simply by asserting it. If a key is already a broad union, design the API and runtime dispatch carefully so payload correlation is maintained. A discriminated message union can make the event name and payload travel together, but it still needs a decoder at an external boundary.
Define delivery and lifecycle
A handler type such as Handler<K> = (payload: Events[K]) => void describes the payload the callback may receive. It does not specify when it runs, whether it can throw, how many handlers may be registered, or how they are removed. A delivery function must actually invoke the intended handler with the matching payload. Document ordering and error policy where consumers depend on them. A void callback contract means the caller ignores its return value; it does not guarantee that every implementation literally returns nothing.
A registry or subscription owns the handler references it installs. If removal is supported, retain the same function identity required by the implementation and test that delivery stops after unsubscribe. Decide whether one throwing handler prevents later handlers from running; types alone cannot choose that behavior. Keep synthetic event delivery tests isolated, with no live service or production data.
Decode unknown names and payloads
A typed deliver function constrains checked source calls; it does not inspect an arbitrary network message at runtime. At the boundary, treat incoming data as unknown, check that it is an object, read and validate the event name, and validate the corresponding payload shape before constructing a typed message. For saved, id must satisfy its documented numeric domain; for failed, message must satisfy its text rule. Reject unknown names and mismatched payloads instead of asserting them into the map.
Separate validation from authorization. Even a well-shaped saved event does not prove its sender may perform a protected action. Authenticate and authorize at the trusted boundary and expose safe errors to users. Test null, an unknown event name, a saved payload with a string id, and a valid control. Preserve the correlation when routing the decoded result; do not validate a name and then read an unrelated payload variant.
Test types, decoding, and delivery separately
Compile a valid consumer and deliberate mismatches under the pinned TypeScript 5.7.3 strict flags, including noEmitOnError. Use fresh isolated directories for negative cases, assert the intended diagnostic and absence of new output, and run valid emitted programs in Node 22.23.3. A type test should establish that Handler<"failed"> receives a message string and cannot read a saved-only id. The type does not execute a handler or prove runtime input validity.
Then test the actual decoder and delivery with controlled synthetic values. Assert the selected handler, exact payload, call count, error behavior, and unsubscribe or cleanup policy. Include a malformed network-like input and an authorized valid control in a safe environment. A passing local fixture supports the stated contract; actual transport, security, and lifecycle integration require their own evidence.
20 worked examples
1. Saved payload
Problem: Deliver a synthetic saved event with its numeric identifier.
- The saved key selects the payload shape containing numeric id.
- The handler receives that matching payload and prints identifier seven.
interface Events { saved: { id: number }; failed: { message: string } }
function deliver<K extends keyof Events>(name: K, payload: Events[K], handler: (p: Events[K]) => void): void { handler(payload); }
deliver("saved", { id: 7 }, p => console.log(p.id));
7
Why this result follows: The handler receives that matching payload and prints identifier seven.
2. Failed payload
Problem: Deliver a synthetic failed event with its textual message.
- The failed key selects the payload containing message.
- The handler receives the failure text and prints offline.
interface Events { saved: { id: number }; failed: { message: string } }
function deliver<K extends keyof Events>(name: K, payload: Events[K], handler: (p: Events[K]) => void): void { handler(payload); }
deliver("failed", { message: "offline" }, p => console.log(p.message));
offline
Why this result follows: The handler receives the failure text and prints offline.
3. Reject mismatched payload
Problem: Reject a failed payload supplied to the saved event key.
- The saved payload requires id and does not declare message.
- The checker reports the incompatible fresh payload for the selected key.
interface Events { saved: { id: number }; failed: { message: string } }
function deliver<K extends keyof Events>(name: K, payload: Events[K]): void {}
deliver("saved", { message: "offline" });
TS2353
Why this result follows: The checker reports the incompatible fresh payload for the selected key.
4. Reject unknown key
Problem: Reject an event name absent from the event map.
- The literal unknown is not a key of Events.
- The generic key constraint rejects the unsupported event name.
interface Events { saved: { id: number }; failed: { message: string } }
function deliver<K extends keyof Events>(name: K, payload: Events[K]): void {}
deliver("unknown", { id: 7 });
TS2345
Why this result follows: The generic key constraint rejects the unsupported event name.
5. Failed handler type
Problem: Read the message in a handler specialized to failed.
- Handler<"failed"> selects the failure payload shape.
- The handler receives a message string and prints the supplied text.
interface Events { saved: { id: number }; failed: { message: string } }
type Handler<K extends keyof Events> = (payload: Events[K]) => void;
const h: Handler<"failed"> = p => console.log(p.message);
h({ message: "bad" });
bad
Why this result follows: The handler receives a message string and prints the supplied text.
6. Reject wrong handler field
Problem: Reject saved-only id access in a failed handler.
- The failed payload declares message, not id.
- The checker rejects reading a property belonging only to another variant.
interface Events { saved: { id: number }; failed: { message: string } }
type Handler<K extends keyof Events> = (payload: Events[K]) => void;
const h: Handler<"failed"> = p => console.log(p.id);
TS2339
Why this result follows: The checker rejects reading a property belonging only to another variant.
7. Saved handler type
Problem: Read an identifier in a handler specialized to saved.
- The saved handler payload has a numeric id.
- The handler prints the supplied identifier four from its matching variant.
interface Events { saved: { id: number }; failed: { message: string } }
type Handler<K extends keyof Events> = (payload: Events[K]) => void;
const h: Handler<"saved"> = p => console.log(p.id);
h({ id: 4 });
4
Why this result follows: The handler prints the supplied identifier four from its matching variant.
8. Discriminated message
Problem: Route a saved message whose tag and payload travel together.
- The name tag narrows the message and its payload together.
- The saved branch reads id from its correlated payload.
type Message = { name: "saved"; payload: { id: number } } | { name: "failed"; payload: { message: string } };
function route(m: Message): string { return m.name === "saved" ? String(m.payload.id) : m.payload.message; }
console.log(route({ name: "saved", payload: { id: 7 } }));
7
Why this result follows: The saved branch reads id from its correlated payload.
9. Discriminated failure
Problem: Route a failed message and return its associated reason.
- The failed tag selects the payload containing message.
- The failure branch returns its own reason without using saved-only fields.
type Message = { name: "saved"; payload: { id: number } } | { name: "failed"; payload: { message: string } };
function route(m: Message): string { return m.name === "saved" ? String(m.payload.id) : m.payload.message; }
console.log(route({ name: "failed", payload: { message: "offline" } }));
offline
Why this result follows: The failure branch returns its own reason without using saved-only fields.
10. Reject mismatched message
Problem: Reject a saved message carrying only a failure message.
- The saved variant requires its own payload shape.
- The checker rejects the mismatched fresh object before a new artifact is emitted.
type Message = { name: "saved"; payload: { id: number } } | { name: "failed"; payload: { message: string } };
const m: Message = { name: "saved", payload: { message: "bad" } };
console.log(m);
TS2322
Why this result follows: The checker rejects the mismatched fresh object before a new artifact is emitted.
11. Decode valid saved
Problem: Validate an unknown saved message before reading its identifier.
- The synthetic input has the expected object, tag, and numeric id.
- The runtime checks pass before the decoder returns identifier seven.
function decode(x: unknown): number | undefined { if (typeof x !== "object" || x === null || !("name" in x) || x.name !== "saved" || !("payload" in x) || typeof x.payload !== "object" || x.payload === null || !("id" in x.payload) || typeof x.payload.id !== "number") return undefined; return x.payload.id; }
console.log(decode({ name: "saved", payload: { id: 7 } }));
7
Why this result follows: The runtime checks pass before the decoder returns identifier seven.
12. Decode null
Problem: Reject a null network-like value before property access.
- Null fails the explicit non-null object condition.
- The boundary rejects null before attempting to read an event name.
function isObject(x: unknown): boolean { return typeof x === "object" && x !== null; }
console.log(isObject(null));
false
Why this result follows: The boundary rejects null before attempting to read an event name.
13. Reject unknown event
Problem: Reject an unsupported event name at a runtime boundary.
- The synthetic name matches neither allowed event literal.
- The runtime name check rejects other without relying on an erased type.
function validName(x: unknown): boolean { return x === "saved" || x === "failed"; }
console.log(validName("other"));
false
Why this result follows: The runtime name check rejects other without relying on an erased type.
14. Reject wrong id type
Problem: Reject a saved payload whose id is text rather than number.
- The id property exists but its runtime value is a string.
- The numeric field check rejects the mismatched payload representation.
const payload: unknown = { id: "7" };
const ok = typeof payload === "object" && payload !== null && "id" in payload && typeof payload.id === "number";
console.log(ok);
false
Why this result follows: The numeric field check rejects the mismatched payload representation.
15. Validate failure message
Problem: Accept a synthetic failure payload containing a string message.
- The object has a message property whose value is a string.
- The field-type guard accepts this valid failure-payload control.
const payload: unknown = { message: "offline" };
const ok = typeof payload === "object" && payload !== null && "message" in payload && typeof payload.message === "string";
console.log(ok);
true
Why this result follows: The field-type guard accepts this valid failure-payload control.
16. Handler call count
Problem: Record one delivery to a synthetic saved handler.
- The delivery function invokes the supplied callback once.
- The synthetic counter records one call for this single delivery.
interface Events { saved: { id: number } }
let calls = 0; function deliver<K extends keyof Events>(name: K, p: Events[K], h: (x: Events[K]) => void): void { h(p); }
deliver("saved", { id: 1 }, () => { calls++; }); console.log(calls);
1
Why this result follows: The synthetic counter records one call for this single delivery.
17. Handler throws
Problem: Observe a controlled handler error at its delivery owner.
- The handler throws while the delivery function is invoking it.
- The surrounding owner catches the error under this explicit propagation policy.
function deliver(h: () => void): void { h(); }
try { deliver(() => { throw new Error("bad"); }); } catch (e) { console.log(e instanceof Error ? e.message : "unknown"); }
bad
Why this result follows: The surrounding owner catches the error under this explicit propagation policy.
18. Unsubscribe handler
Problem: Remove a saved synthetic handler and avoid a later delivery.
- The same function reference is removed before the iteration.
- No registered handler remains, so the later synthetic delivery records zero calls.
const handlers = new Set<() => void>(); let calls = 0; const h = () => { calls++; };
handlers.add(h); handlers.delete(h); handlers.forEach(f => f()); console.log(calls);
0
Why this result follows: No registered handler remains, so the later synthetic delivery records zero calls.
19. Ignored callback result
Problem: Pass a value-returning handler to a void callback contract.
- The delivery contract ignores the callback return value.
- The handler may return seven, but the consumer does not use that result.
function deliver(h: () => void): void { h(); }
deliver(() => 7); console.log("done");
done
Why this result follows: The handler may return seven, but the consumer does not use that result.
20. Separate authorization
Problem: Compare a valid event shape with a denied synthetic role.
- The payload-shape result and trusted role check answer different questions.
- A well-shaped message is still denied by the separate synthetic authorization rule.
const validShape = true; const role = "viewer" as string;
console.log(validShape, role === "admin" ? "allow" : "deny");
true deny
Why this result follows: A well-shaped message is still denied by the separate synthetic authorization rule.
Common errors and fixes
An event name and payload disagree
- Why it happens
- The name and payload were typed as unrelated unions.
- How to fix it
- Use a key-to-payload relationship at the call boundary.
- Prevent it next time
- Add type tests for each name with both correct and incorrect payloads.
Malformed socket data reaches a handler
- Why it happens
- An assertion treated untrusted data as a typed event.
- How to fix it
- Validate the name and payload at runtime before delivery.
- Prevent it next time
- Keep malformed-message fixtures alongside the typed API tests.
A handler remains registered after its owner is gone
- Why it happens
- The API defined payload types but no subscription lifecycle.
- How to fix it
- Expose and call an unsubscribe operation in the real registry.
- Prevent it next time
- Test disposal and repeated mounting independently of type checks.
20 practice exercises
1. What payload does Handler<"failed"> receive?
Show hint
Index the event map with the failed key.
Show worked solution
It receives the failed payload, which has a message string. Accessing id as though it were a saved payload is not justified. The mapping keeps this relationship in one shared declaration.
Handler<"failed"> receives the failed payload {message: string}. It can read message but cannot assume the saved-only id field. The shared event map preserves that relationship; test valid failed delivery and a negative id access separately.
Check your solution
- The failed payload contains message text.
- The failed handler does not assume a saved id.
2. Does deliver prevent malformed network messages?
Show hint
Typed calls are not a runtime decoder for network data.
Show worked solution
No. Its types constrain checked calls but do not inspect a network message at runtime. A boundary validator must verify the name and corresponding payload before constructing arguments for deliver.
deliver constrains checked source calls but does not inspect a network message. A boundary validator must verify the name and corresponding payload before constructing typed arguments. Reject malformed data and enforce authorization for protected effects separately.
Check your solution
- Unknown names and mismatched payloads are rejected at runtime.
- Only validated arguments reach delivery.
3. Define payloads for saved with numeric id and failed with string message.
Show hint
Place the relationship in one event map.
Show worked solution
Define Events with saved: {id: number} and failed: {message: string}. Handler<"saved"> receives the id payload, while Handler<"failed"> receives the message payload. Test valid calls for both and a mismatched pair in a separate negative compilation.
Check your solution
- Saved carries numeric id
- Failed carries string message
4. Determine which field Handler<"failed"> can read and reject saved-only access.
Show hint
Index the event map with the failed key.
Show worked solution
Handler<"failed"> receives {message: string}, so it can read message. It cannot assume the saved-only id field exists. Compile a valid message handler and a negative id access separately, then test actual delivery with a synthetic failure message.
Check your solution
- The failed handler reads message
- Saved-only id access is rejected
5. Explain how K extends keyof Events relates a delivery key to Events[K].
Show hint
The chosen key selects its matching payload type.
Show worked solution
The constraint allows only keys in Events and the indexed access selects the payload for that key. A literal "saved" call requires its id payload; a literal "failed" call requires its message payload. Test both valid pairs and a mismatched fresh payload.
Check your solution
- Saved requires id
- Failed requires message
6. Explain why independent unions of event names and payloads can lose correlation.
Show hint
A name and unrelated payload can otherwise be combined.
Show worked solution
If the signature accepts a name union and a separate payload union without connecting them, it may permit "saved" with a failed payload. Use a key-dependent relationship or discriminated message union and test mismatched combinations. Runtime decoding is still needed for external messages.
Check your solution
- Mismatched name and payload are rejected
- External messages are decoded separately
7. Use a discriminated message union to route saved id 7 and failed message "offline".
Show hint
Check the name tag before reading variant-specific payload fields.
Show worked solution
Model each message as a name literal paired with its payload, then branch on name. The saved branch reads id 7; the failed branch reads "offline". Test both and reject a saved message carrying only a failed payload in a negative static case.
Check your solution
- Saved routing reads id 7
- Failed routing reads offline
8. Explain why deliver types do not prevent malformed network messages.
Show hint
Type declarations do not inspect unknown data at runtime.
Show worked solution
The signature constrains checked source calls but is erased from JavaScript. A network boundary must validate the actual object, allowed name, and matching payload fields before constructing arguments for deliver. Test null, unknown names, wrong payload types, and a valid control.
Check your solution
- Malformed messages are rejected at runtime
- The typed delivery receives validated arguments
9. Validate an unknown saved message with numeric id 7 before delivery.
Show hint
Check object, tag, payload object, and id type and domain.
Show worked solution
Require a non-null object with name "saved" and a payload object whose id satisfies the documented numeric rule. Construct the typed message only after those checks, then deliver id 7. Reject a string id and enforce any product-specific identifier range.
Check your solution
- The valid message delivers id 7
- A string id is rejected
10. Validate an unknown failed message containing the text "offline".
Show hint
Check the name and corresponding message field together.
Show worked solution
Require a non-null message object named "failed" with a payload object whose message is a string satisfying the product rule. The valid fixture can deliver "offline"; missing or numeric message fields must fail before the handler runs.
Check your solution
- The valid message is delivered
- Missing or numeric message is rejected
11. Explain why a valid event payload is not proof that its sender is authorized.
Show hint
Shape validation and authorization are separate boundaries.
Show worked solution
A well-shaped saved payload only establishes the checked data contract. Authenticate and authorize the source at the trusted boundary before a protected effect, and test denial with a synthetic lower-privilege identity. Do not infer permission from a TypeScript event name.
Check your solution
- Payload shape is validated
- Protected effects require separate authorization
12. Test that a saved handler receives id 7 exactly once for one delivery.
Show hint
Use a synthetic handler that records payloads.
Show worked solution
Deliver the validated saved payload {id: 7} to a recording handler, then assert one call and the recorded id 7. Await the operation if the delivery contract is asynchronous. A call count alone does not verify the payload value.
Check your solution
- Exactly one call is recorded
- The recorded payload id is 7
13. Define a handler error policy and test a controlled thrown error.
Show hint
Decide whether delivery propagates or isolates handler failures.
Show worked solution
Document whether a throwing handler stops later delivery or is isolated, and who observes the error. In a propagation policy, use a synthetic handler that throws "bad" and assert the owner catches it. Do not infer this behavior from Handler<K> alone.
Check your solution
- The chosen error policy is explicit
- A controlled failure reaches its owner
14. Test unsubscribe using the same handler reference that was registered.
Show hint
Function identity matters to a reference-based registry.
Show worked solution
Register a recording handler, remove that same function reference, then deliver another synthetic event and assert no new call. Also test delivery before removal. A newly created function with identical source text is a different reference and may not remove the original.
Check your solution
- The registered handler receives the first event
- No call occurs after matching removal
15. Explain what a void handler return type says about a returned number.
Show hint
The consumer ignores the return through that callback contract.
Show worked solution
A void callback contract tells the caller not to use the result; TypeScript can accept an implementation that returns a value in that contextual position. It does not guarantee the implementation literally returns nothing. Test side effects and errors separately.
Check your solution
- The delivery caller ignores the result
- Invocation and errors have separate tests
16. Design a static negative test for saved paired with a failed payload.
Show hint
Compile the mismatched fresh payload separately.
Show worked solution
Compile a literal "saved" call carrying {message: "bad"} and assert the intended payload diagnostic with no fresh output under noEmitOnError. Compile valid saved {id: 7} and failed {message: "bad"} controls separately and run their handlers.
Check your solution
- The mismatched pair is diagnosed
- Both valid pairs compile and run
17. Test a decoder with null, an unknown event name, and a string saved id.
Show hint
Each malformed category should fail before delivery.
Show worked solution
Assert null is rejected before property access, {name: "other"} is rejected as an unknown event, and saved with id "7" is rejected for type. Add a valid saved id 7 control and assert no invalid case calls the handler.
Check your solution
- All three malformed inputs are rejected
- The valid control delivers id 7
18. Explain why a broad union key needs care when preserving payload correlation.
Show hint
A key and payload can become independent unions.
Show worked solution
If a key is already a union rather than a specific literal, ensure the API does not pair it with an unrelated payload union without preserving their relationship. A discriminated message union can carry both together. Validate and route external messages at runtime.
Check your solution
- Name and payload remain correlated
- Unknown input is validated before routing
19. Design evidence for a keyed event API beyond successful type inference.
Show hint
Cover type pairs, decoding, delivery, and lifecycle.
Show worked solution
Compile valid and mismatched name-payload pairs, then run a synthetic decoder against valid and malformed messages. Assert handler identity, payload, call count, controlled error policy, and unsubscribe behavior. Verify authorization and actual transport separately in an isolated environment.
Check your solution
- Static and runtime boundaries are exercised
- Lifecycle and authorization have separate evidence
20. Explain what a passing local event-map test cannot prove about a deployed service.
Show hint
Limit the conclusion to the synthetic fixture and runtime.
Show worked solution
It supports the checked relationship and observed handler behavior for its stated inputs and compiler configuration. It does not prove network decoding, server authorization, delivery guarantees, or production lifecycle. Test those actual boundaries separately with authorized synthetic data and document assumptions.
Check your solution
- The local relationship is verified
- Transport and authorization remain separate checks
Key takeaways
- A generic key and indexed access express the event-to-payload relationship.
- Type checks complement runtime validation and lifecycle tests.
- Handler<"failed"> receives the failure message payload, not a saved id.
- A typed delivery signature does not validate arbitrary network input.
- Handler ordering, errors, and removal require explicit runtime contracts.