1
votes

Observation

I found that my code editor (vscode) is not complaining about line 5. So I thought that it was just a typescript extension bug. But when I compiled it (tsc), it was successfully compiled.

class A {}
class B {}
class C {}
type X = A | B;
let x: X = new C();

Further observation

When I defined class A and class B with some member fields/methods and leaves class C empty, then compilation fails. And I defined class D and class E with member fields/methods are the same with the either of class A or class B, then it compiles successfully

class A {public a: string;}
class B {public f() {};}
class C {}
class D {public a: string;}
class E {public f() {};}
type X = A | B;
let x: X = new C(); // fail
let y: X = new D(); // success
let z: X = new E(); // success

Even further observation

In the above example, below gives me false, false and true.

console.log(y instanceof A);
console.log(y instanceof B);
console.log(y instanceof D);

Question

Does tsc checks type equality/assignability not with class name but with member signature ?

(all tests done with tsc --version = 3.8.3)

1

1 Answers

2
votes

Yes, typescript has structural type system.

Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. This is in contrast with nominal typing

More info on type compatibility here.