Worker message models
Concept and boundary
Model worker messages as discriminated unions and decode unknown incoming data before processing it. A MessageEvent type argument documents a convention, but a sender can post an incompatible value. Here the decoder and handler run without a worker.
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 Msg={kind:"sum";n:number}|{kind:"stop"}; function decode(x:unknown):Msg|undefined{if(typeof x!=="object"||x===null||!("kind" in x))return;if(x.kind==="stop")return {kind:"stop"};if(x.kind==="sum"&&"n" in x&&typeof x.n==="number")return {kind:"sum",n:x.n};} const m=decode({kind:"sum",n:4}); console.log(m?.kind==="sum"?m.n*2:0);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:
8Rejected project — diagnosis
Intentionally rejected variant. Do not execute it.
Use a fresh copy of the accepted project, changing only the files shown below.
type Msg={kind:"sum";n:number}|{kind:"stop"}; const m:Msg={kind:"sum",n:"4"};From the project root run: tsc -p tsconfig.json --pretty false.
Expected compiler diagnostic: TS2322
No runtime execution is required for this check.
The sum message requires numeric n. Restore the accepted configuration/source to compare the result.
Practice and recap
Reject a message with an unknown kind and test stop separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Worker message models — knowledge check
Check the concept, interpret the tested project result, and diagnose a rejected configuration or source.
Which statement correctly describes Worker message models?
Using the complete accepted project and the exact command in the lesson, which result is expected?
type Msg={kind:"sum";n:number}|{kind:"stop"}; function decode(x:unknown):Msg|undefined{if(typeof x!=="object"||x===null||!("kind" in x))return;if(x.kind==="stop")return {kind:"stop"};if(x.kind==="sum"&&"n" in x&&typeof x.n==="number")return {kind:"sum",n:x.n};} const m=decode({kind:"sum",n:4}); console.log(m?.kind==="sum"?m.n*2:0);Why does the rejected project fail under its stated configuration?
type Msg={kind:"sum";n:number}|{kind:"stop"}; const m:Msg={kind:"sum",n:"4"};