38. Intersection types
Module 8 · approximately 20 minutes
Open Interactive LessonDiscover and predict
What does intersection types let the compiler check, and what still needs a runtime test?
Understand
An intersection combines requirements, often to compose small capabilities. It is not a set of common object keys and does not select the runtime overlap of two objects. A value must have all required fields with compatible types. Conflicting primitives can reduce to never; inspect the compiler’s actual result instead of relying on a misleading Venn diagram.
Important source operations
- Line 1:
type HasId={id:string}; - This declaration describes a static contract and does not construct or validate runtime data. Actual checker declaration information: HasId: { id: string; }.
- Line 2:
type HasState={state:"open"|"closed"}; - This declaration describes a static contract and does not construct or validate runtime data. Actual checker declaration information: HasState: { state: "open" | "closed"; }.
- Line 3:
const task:HasId & HasState={id:"T1",state:"open"}; - Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: task: HasId & HasState.
- Line 4:
console.log(task.state); - Observe the actual runtime value. A log is evidence for this input, not proof of every permitted value.
Working concept in practice
An intersection combines requirements, often to compose small capabilities. It is not a set of common object keys and does not select the runtime overlap of two objects. A value must have all required fields with compatible types. Conflicting primitives can reduce to never; inspect the compiler’s actual result instead of relying on a misleading Venn diagram.
main.ts
type HasId={id:string};
type HasState={state:"open"|"closed"};
const task:HasId & HasState={id:"T1",state:"open"};
console.log(task.state);Exact authored reference result
{
"diagnostics": [],
"logs": [
"open"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Investigate the compiler or runtime fault
Predict the result of the supplied wrong operation. Read actual compiler feedback; if it compiles, investigate the real runtime mismatch instead. Fault: {id:"T1",state:42}
main.ts
type HasId={id:string};
type HasState={state:"open"|"closed"};
const task:HasId & HasState={id:"T1",state:42};
console.log(task.state);Exact authored reference result
{
"diagnostics": [
{
"code": 2322,
"category": "Error",
"message": "Type 'number' is not assignable to type '\"open\" | \"closed\"'.",
"file": "main.ts",
"line": 3,
"column": 38,
"start": 100,
"length": 5
}
],
"logs": [],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
A compiler-clean behavioral counterexample
The display output changes while its values remain type-compatible. Static checking does not prove that UI or log content matches the required wording. This intentionally incorrect program demonstrates why runtime tests remain necessary.
main.ts
type HasId={id:string};
type HasState={state:"open"|"closed"};
const task:HasId & HasState={id:"T1",state:"open"};
console.log("Unexpected display", task.state);Exact authored reference result
{
"diagnostics": [],
"logs": [
"Unexpected display open"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
An executable behavior contract
Capture the actual observable result and assert the independently authored expected output. This optional professional test pattern introduces helper/rest/async syntax; focus on the primary example first if those concepts are new.
main.ts
const __observed:string[]=[];
function __capture(...values:unknown[]):void{__observed.push(values.map(value=>typeof value==="string"?value:typeof value==="undefined"?"undefined":typeof value==="number"&&!Number.isFinite(value)?String(value):JSON.stringify(value)??String(value)).join(" "));}
type HasId={id:string};
type HasState={state:"open"|"closed"};
const task:HasId & HasState={id:"T1",state:"open"};
__capture(task.state);
async function verifyContract():Promise<void>{await new Promise<void>(resolve=>setTimeout(resolve,15));const expected:string[]=["open"];if(JSON.stringify(__observed)!==JSON.stringify(expected))throw new Error("Behavior contract failed");console.log("Contract verified");}
verifyContract().catch(error=>console.log(error instanceof Error?error.message:String(error)));Exact authored reference result
{
"diagnostics": [],
"logs": [
"Contract verified"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Transfer to another useful feature
Apply the topic in a different small task. Predict the output and identify the type/runtime boundary before editing.
main.ts
type Positioned={x:number;y:number};type Named={name:string};
const marker:Positioned & Named={x:4,y:7,name:"Start"};
console.log(marker.name + ": " + marker.x);Exact authored reference result
{
"diagnostics": [],
"logs": [
"Start: 4"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Build and test
Repair the supplied source so it compiles under the lesson settings and produces open. Equivalent implementations may pass the observable contract.
Hint 1
Read the first meaningful diagnostic and its source location, or compare the first runtime mismatch when the program compiles.
Hint 2
The exercise changes {id:"T1",state:"open"} to {id:"T1",state:42}. Determine whether the contract, caller or business operation is wrong.
Hint 3
Restore {id:"T1",state:"open"} or implement an equivalent correct contract. Do not hide the issue with any or an unjustified assertion; run the stated behavior check.
Explain, reflect and extend
Explain which evidence came from the compiler and which came from execution. Give a second input and a predicted result. What assumption could still fail outside this example?
Extend the useful feature with a boundary case and one invalid external input. Write the expected behavior first, then verify it using actual diagnostics and tests.
Troubleshooting
Verify the active filename, first diagnostic, actual inferred/flow type and emitted output. A type error blocks emission in this lab; an empty runtime pane is not a fabricated success. Browser examples require the DOM preview, while worker execution has no document. Project imports must refer to supplied relative files. Check runtime validation and logical operators when clean compilation still produces the wrong result.