Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 275
KarolDepka Avatar asked Mar 11 '23 06:03

KarolDepka


2 Answers

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

like image 146
shusson Avatar answered Mar 24 '23 17:03

shusson


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.

like image 39
Rob Avatar answered Mar 24 '23 16:03

Rob