In the following code, I am trying to work with an instance of class Test after a type check.
main.ts
class Test {
x: number = 0;
test() {}
}
let t1: Test | number = new Test();
if (t1 instanceof Test) {
console.log(t1.x); // works
let t2 = new Test();
t2.test = function() {
this.x = t1.x; // doesn't work
}
}
After running tsc main.ts
I get:
main.ts:12:21 - error TS2339: Property 'x' does not exist on type 'number | Test'.
Property 'x' does not exist on type 'number'.
12 this.x = t1.x; // doesn't work
~
Found 1 error.
tsc --version
returns Version 3.4.5
The problem is, that the t1
is defined with let
, it means in the runtime, when the test
function on t2
is called, it could have been already changed and not been of type Test
anymore (well, not in the snippet, but from the compiler point of view, you can write some code after the function definition).
If you change the definition to const
, it works fine:
class Test {
x: number = 0;
test() {}
}
const t1: Test | number = new Test();
if (t1 instanceof Test) {
console.log(t1.x); // works
let t2 = new Test();
t2.test = function() {
this.x = t1.x; // works fine
}
}