Are union types used?

Is this really not so?

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 any way to force type control in this case?

+4
source share
2 answers

TypeScript handles type-based compatibility structural subtyping.

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

In particular, for classes:

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

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

+4
source

, Animal Person -:

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

Animal Person, ( -, ) , .

+3

Source: https://habr.com/ru/post/1665810/


All Articles