Instanceof and in guards
Concept and syntax
instanceof tests a runtime prototype relationship; in tests whether a property exists (including inherited properties). TypeScript uses these observations to narrow unions. Optional properties can occur on both sides of an in test. Neither check proves a complete external object schema.
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.
function show(x:Date|{label:string}){ if(x instanceof Date) return String(x.getUTCFullYear()); if("label" in x) return x.label; return "?"; }console.log(show(new Date("2020-01-01T00:00:00Z")),show({label:"tea"}));Expected output:
2020 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
function show(x:Date|{label:string}){ return x.getUTCFullYear(); }Expected diagnostic: TS2339. The object alternative is not a Date; test instanceof Date first.
Practice and recap
Use in to discriminate two objects with distinct required keys.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Instanceof and in guards — 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)?
function show(x:Date|{label:string}){ if(x instanceof Date) return String(x.getUTCFullYear()); if("label" in x) return x.label; return "?"; }console.log(show(new Date("2020-01-01T00:00:00Z")),show({label:"tea"}));Which diagnostic and explanation match the rejected example under the lesson settings?
function show(x:Date|{label:string}){ return x.getUTCFullYear(); }