Union member access
Concept and syntax
A union A | B accepts values from either type. Before narrowing, use only operations supported by every possible member. A shared property is safe even when other properties differ; the runtime object still has its actual shape. Use a branch to establish which member you have.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type Item = {id:number; text:string} | {id:number; size:number};function read(x:Item){ return x.id; }console.log(read({id:3,text:"tea"}), read({id:4,size:8}));Expected output:
3 4Common mistake
Intentionally invalid; compile separately and do not execute.
type Item = {id:number; text:string} | {id:number; size:number};function read(x:Item){ return x.text; }Expected diagnostic: TS2339. text is not shared. Check "text" in x before accessing it.
Practice and recap
Add a shared boolean field, then read it from both variants.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Union member access — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Item = {id:number; text:string} | {id:number; size:number};function read(x:Item){ return x.id; }console.log(read({id:3,text:"tea"}), read({id:4,size:8}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Item = {id:number; text:string} | {id:number; size:number};function read(x:Item){ return x.text; }