【问题标题】:Why is there no weak type detection on a empty object为什么对空对象没有弱类型检测
【发布时间】:2021-02-10 20:34:13
【问题描述】:

我正在阅读 typescript 文档并遇到以下问题。

TypeScript 2.4 引入了“弱类型”的概念。任何类型的 只包含一组全可选属性被认为是 弱一点。

在 TypeScript 2.4 中,如果属性没有重叠,现在将任何内容分配给弱类型是错误的。

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

【问题讨论】:

  • 我认为您应该阅读:在 TypeScript 2.4 中,当存在不重叠的属性时,现在将任何内容分配给弱类型是错误的。
  • 我想这就是我引用的地方。
  • 它在单词的语义中。空对象等于部分对象。当您的对象包含不属于部分的属性时,这是一个错误。
  • @Silvermind。伟大的。非常感谢。我不知道部分是什么。会调查的。

标签: typescript object interface


【解决方案1】:

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

这意味着:如果有属性,但没有一个与部分属性匹配。 换句话说:如果您分配的对象没有目标类型中存在的属性,则会产生错误。

partial 实际上与空对象 {} 相同。

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> = { };

如果您将 name 属性添加到动物类型,它会接受它。

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2015-04-03
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2021-02-22
    • 2011-11-15
    • 2020-11-30
    相关资源
    最近更新 更多