42. Narrowing with instanceof
Module 9 · approximately 20 minutes
Open Interactive LessonDiscover and predict
What does narrowing with instanceof let the compiler check, and what still needs a runtime test?
Understand
instanceof checks a runtime prototype relationship. It is useful for classes such as Date or custom classes that actually exist at runtime, but interfaces and aliases are erased and cannot be instanceof targets. Cross-realm objects can complicate this check. Prefer structural validation for plain JSON data rather than assuming it has a class prototype.
Important source operations
- Line 1:
function year(value:Date|string):string { - Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: year: (value: Date | string) => string; value: string | Date.
- Line 2:
if(value instanceof Date) return String(value.getUTCFullYear()); - The return expression must satisfy the declared or inferred signature. Its business meaning still needs independent tests.
- Line 3:
return value; - The return expression must satisfy the declared or inferred signature. Its business meaning still needs independent tests.
- Line 4:
} - Follow the value relationship and inspect compiler information at this source position.
- Line 5:
console.log(year(new Date("2026-01-01T00:00:00Z"))); - Observe the actual runtime value. A log is evidence for this input, not proof of every permitted value.
Working concept in practice
instanceof checks a runtime prototype relationship. It is useful for classes such as Date or custom classes that actually exist at runtime, but interfaces and aliases are erased and cannot be instanceof targets. Cross-realm objects can complicate this check. Prefer structural validation for plain JSON data rather than assuming it has a class prototype.
main.ts
function year(value:Date|string):string {
if(value instanceof Date) return String(value.getUTCFullYear());
return value;
}
console.log(year(new Date("2026-01-01T00:00:00Z")));Exact authored reference result
{
"diagnostics": [],
"logs": [
"2026"
],
"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: year(42)
main.ts
function year(value:Date|string):string {
if(value instanceof Date) return String(value.getUTCFullYear());
return value;
}
console.log(year(42));Exact authored reference result
{
"diagnostics": [
{
"code": 2345,
"category": "Error",
"message": "Argument of type 'number' is not assignable to parameter of type 'string | Date'.",
"file": "main.ts",
"line": 5,
"column": 18,
"start": 144,
"length": 2
}
],
"logs": [],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
A compiler-clean behavioral counterexample
A type-compatible text value differs from the intended content. The compiler checks type relationships, not the accuracy of arbitrary text. This intentionally incorrect program demonstrates why runtime tests remain necessary.
main.ts
function year(value:Date|string):string {
if(value instanceof Date) return String(value.getUTCFullYear());
return value;
}
console.log(year(new Date("2026-01-01T00:00:00Z!")));Exact authored reference result
{
"diagnostics": [],
"logs": [
"NaN"
],
"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(" "));}
function year(value:Date|string):string {
if(value instanceof Date) return String(value.getUTCFullYear());
return value;
}
__capture(year(new Date("2026-01-01T00:00:00Z")));
async function verifyContract():Promise<void>{await new Promise<void>(resolve=>setTimeout(resolve,15));const expected:string[]=["2026"];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
class Notice { constructor(public text:string){} }
function read(value:Notice|string):string{return value instanceof Notice?value.text:value;}
console.log(read(new Notice("Ready")));Exact authored reference result
{
"diagnostics": [],
"logs": [
"Ready"
],
"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 2026. 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 year(new Date("2026-01-01T00:00:00Z")) to year(42). Determine whether the contract, caller or business operation is wrong.
Hint 3
Restore year(new Date("2026-01-01T00:00:00Z")) 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.