The following code gives errors:
enum E { FIRST = 1, SECOND = 2 };
class C {
value: E;
constructor(arg: C | E) {
if (arg instanceof C) { // 1.
this.value = arg.value;
} else {
this.value = arg; // 2.
}
}
}
var a: C = new C(E.SECOND);
console.log('a.value = ' + a.value);
var b: C = new C(a);
console.log('b.value = ' + b.value);
Despite the errors the code seems to compile fine on TypeScript Playground and does the expected.
Two issues.
There's a bug in the compiler that instanceof
isn't allowed on union types when one of its constituents isn't an object type. This is being fixed (https://github.com/Microsoft/TypeScript/issues/2775)
The other thing is that instanceof
does not cause narrowing in the else
block (https://github.com/Microsoft/TypeScript/issues/1719) because failing an instanceof
check doesn't necessarily mean the object doesn't match the specified interface. This is currently "by design" but I'd encourage you to leave a comment that you find this behavior surprising or undesirable (I certainly do).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With