javascript - 对象文字。不精确类型与精确类型不兼容(没有对象传播)

标签 javascript flowtype

在以下情况下,Flow 可以正确处理精确类型:

type Something={|a: string|};
const x1: Something = {a: '42'};        // Flow is happy
const x2: Something = {};               // Flow correctly detects problem
const x3: Something = {a: '42', b: 42}; // --------||---------

...然而 Flow 也提示以下内容:

type SomethingEmpty={||};
const x: SomethingEmpty = {}; 

消息是:

object literal. Inexact type is incompatible with exact type

这与 this one 不同因为没有使用点差。

使用最新的 0.57.3 进行测试。

最佳答案

没有属性的 Object 文字在 Flow 中被推断为未密封的对象类型,这意味着您可以向此类对象添加属性或解构不存在的属性而不会引发错误:

// inferred as...

const o = {}; // unsealed object type
const p = {bar: true} // sealed object type

const x = o.foo; // type checks
o.bar = true; // type checks

const y = p.foo; // type error
p.baz = true; // type error

Try

要将空的 Object 字面量键入为不带属性的精确类型,您需要显式地密封它:

type Empty = {||};
const o :Empty = Object.seal({}); // type checks

Try

关于javascript - 对象文字。不精确类型与精确类型不兼容(没有对象传播),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840089/

相关文章:

javascript - 是否可以从模块声明中导入类型?

javascript - 如何检查缩小是否出错?

javascript - webpack 包中的必需模块未定义

javascript - 如何仅针对Angular7中的字母数字和特殊字符触发keydown事件?

react-native - react-native中flow和eslint有什么区别?我应该使用哪一个?我可以同时使用吗?

javascript - 缺少 `T` 的类型注释

reactjs - 流类型 React ref 回调和 createRef

javascript - TypeScript 中多种类型的参数类型

javascript - 如何缩短 JavaScript 的正则表达式?

javascript - IOREDIS - 尝试从 Redis 迁移到 KeyDB 时出错