Here is a code snippet that raises an error in TypeScript:
class Status { constructor(public content: string){} }
class Visitor
{
private status: Status | undefined = undefined;
visit(tree: Tree) {
if (tree.value > 7) {
this.status = new Status("good");
return; // oops ! forgot this return statement
}
this.status = undefined;
if (tree.left) { tree.left.accept(this); }
if (this.status === undefined) { return; }
// incorrectly infer this.status to be never
console.log(this.status.content);
}
}
class Tree {
constructor(public value: number, public left?: Tree, public right?: Tree){}
accept(visitor: Visitor) {
visitor.visit(this);
}
}
Upon compiling the code using npx tsc --strict main.ts
, the following error is generated:
% npx tsc --strict main.ts
main.ts:16:29 - error TS2339: Property 'content' does not exist on type 'never'.
16 console.log(this.status.content);
~~~~~~~
Even after attempting to use this.status!.content
, the error persists.