Typed command and event contracts
Concept and boundary
Map event names to payload types and preserve their correlation with a discriminated union. A handler narrows the event before processing its payload. This protects typed call sites but not messages arriving from untrusted transport.
Accepted project
Create a fresh folder with exactly these files. Use TypeScript 5.8.3 and Node.js 22.16.0. Package stubs under node_modules are local teaching fixtures, not installed dependencies.
type Payloads={added:{id:number};removed:{reason:string}}; type EventMsg={[K in keyof Payloads]:{kind:K;data:Payloads[K]}}[keyof Payloads]; function handle(e:EventMsg){return e.kind==="added"?String(e.data.id):e.data.reason;} console.log(handle({kind:"removed",data:{reason:"done"}}));tsconfig.json
{ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "moduleResolution": "Node10", "moduleDetection": "force", "skipLibCheck": true, "noEmitOnError": true, "types": [] }, "include": [ "**/*" ], "exclude": [ "node_modules", "dist", "build", "cache" ]}From the project root run: tsc -p tsconfig.json --pretty false.
Compilation succeeds (exit 0).
Run node main.js. Expected stdout:
doneRejected project — diagnosis
Intentionally rejected variant. Do not execute it.
Use a fresh copy of the accepted project, changing only the files shown below.
type Payloads={added:{id:number};removed:{reason:string}}; type EventMsg={[K in keyof Payloads]:{kind:K;data:Payloads[K]}}[keyof Payloads]; const e:EventMsg={kind:"added",data:{reason:"done"}};From the project root run: tsc -p tsconfig.json --pretty false.
Expected compiler diagnostic: TS2322
No runtime execution is required for this check.
The discriminant requires the added payload shape. Restore the accepted configuration/source to compare the result.
Practice and recap
Add a renamed event with old and new labels.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed command and event contracts — knowledge check
Check the concept, interpret the tested project result, and diagnose a rejected configuration or source.
Which statement correctly describes Typed command and event contracts?
Using the complete accepted project and the exact command in the lesson, which result is expected?
type Payloads={added:{id:number};removed:{reason:string}}; type EventMsg={[K in keyof Payloads]:{kind:K;data:Payloads[K]}}[keyof Payloads]; function handle(e:EventMsg){return e.kind==="added"?String(e.data.id):e.data.reason;} console.log(handle({kind:"removed",data:{reason:"done"}}));Why does the rejected project fail under its stated configuration?
type Payloads={added:{id:number};removed:{reason:string}}; type EventMsg={[K in keyof Payloads]:{kind:K;data:Payloads[K]}}[keyof Payloads]; const e:EventMsg={kind:"added",data:{reason:"done"}};