为什么空对象没有弱类型检测

Why is there no weak type detection on a empty object

我正在阅读打字稿文档并遇到以下内容。

TypeScript 2.4 introduces the concept of “weak types”. Any type that contains nothing but a set of all-optional properties is considered to be weak.

In TypeScript 2.4, it’s now an error to assign anything to a weak type when there’s no overlap in properties.

但是,我可以将空对象 {} 分配给弱类型,编译器不会抛出任何错误。 为什么会这样,因为属性没有重叠。

弱类型本质上与Partial<StrongType>相同。

意思是:如果有属性,但没有一个符合partials属性。 换句话说:如果您分配的对象没有目标类型中存在的属性,则会产生错误。

局部对象实际上与空对象相同{}

interface Person {
  name: string;
}

interface Animal {
  animalType: string;
}

const animal: Animal = {
  animalType: 'cow'
};

// Type 'Animal' has no properties in common with type 'Partial<Person>'.
const personPartial: Partial<Person> = animal;

// Valid, there are no additional properties
const personPartial2: Partial<Person> = { };

如果您为动物类型添加名称 属性,它会接受它。