Are union types not enforced?

214 views Asked by At

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?

2

There are 2 answers

2
shusson On BEST ANSWER

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

4
Rob On

It'll fail if Animal or Person define anything:

class Animal { name: string; }
class Person { age: Number; }

type MyUnion = Number | Person;

var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Fails now

var x: MyUnion = "jjj"; // Fails now

Since you haven't defined anything in Animal or Person, a string (or anything, actually), fulfills the contract you're asking for.