是否不强制执行联合类型?

Are union types not enforced?

这不应该失败吗?

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?

在这种情况下有没有办法强制执行类型检查?

如果 AnimalPerson 定义任何内容,它将失败:

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

由于您没有在 AnimalPerson 中定义任何内容,因此字符串(或任何其他内容)满足您要求的合同。

TypeScript 根据 structural subtyping.

处理类型兼容性

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

特别是 类:

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

更多信息请访问 https://www.typescriptlang.org/docs/handbook/type-compatibility.html#classes