Search code examples
typescripttypecheckingstatic-typingunion-types

Are union types not enforced?


Shouldn't this fail?

class Animal { }
class Person { }

type MyUnion = Number | Person;

var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Shouldn't this fail?

var x: MyUnion = "jjj"; // Shouldn't this fail?

Is there a way to enforce type checking in this case?


Solution

  • TypeScript handles type compatibility based on structural subtyping.

    Structural typing is a way of relating types based solely on their members

    In particular for classes:

    When comparing two objects of a class type, only members of the instance are compared. Static members and constructors do not affect compatibility.

    More info at https://www.typescriptlang.org/docs/handbook/type-compatibility.html#classes