【问题标题】:Why does Flowtype allow assigning empty object ({}) to a type?为什么 Flowtype 允许将空对象 ({}) 分配给类型?
【发布时间】:2019-07-26 05:38:01
【问题描述】:

有人可以向我解释为什么a2 没有给出任何错误吗?

type A = {
 name: string;
 type: number;
}; 

const a1: A = null; // NOT OK
const a2: A = {}; // OK
const a3: A = { name: "aaa" }; // NOT OK
const a4: A = { name: "aaa", type: 6 }; // OK

我在 Typescript 中尝试了相同的操作,但 a2 无法编译。我同意打字稿。为什么 Flowtype 认为没问题?有没有可以让我让它不正常的设置?

【问题讨论】:

  • 我知道我可以使用精确类型使其失败,但这不是我想要的。它可以在 Typescript 上按预期工作,但不能在 Flow 上工作。为什么?
  • 我觉得和issue #2327有关。

标签: flowtype


【解决方案1】:

{} 似乎是一个特殊的东西——未密封的对象(https://flow.org/en/docs/types/objects/#toc-unsealed-objects)。这个想法是让您逐步填充对象:

type A = {
 name: string;
 type: number;
}; 

const a2: A = {};
a2.name = "FOO";
a2.type = 3;

对于它应该如何在各种不同的情况下准确工作似乎存在很多困惑:

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2021-10-21
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多