对象字面量。不精确类型与精确类型不兼容(没有对象传播)

Mar*_*tus 5 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}; // --------||---------
Run Code Online (Sandbox Code Playgroud)

……但是 Flow 还抱怨以下内容:

type SomethingEmpty={||};
const x: SomethingEmpty = {}; 
Run Code Online (Sandbox Code Playgroud)

讯息是:

object literal. Inexact type is incompatible with exact type
Run Code Online (Sandbox Code Playgroud)

这与这种情况不同,因为没有使用价差。

用最新的0.57.3.

小智 4

没有属性的文字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
Run Code Online (Sandbox Code Playgroud)

尝试

要将空Object文字输入为没有属性的精确类型,您需要显式密封它:

type Empty = {||};
const o :Empty = Object.seal({}); // type checks
Run Code Online (Sandbox Code Playgroud)

尝试

  • 请注意,“seal”不再起作用。当前的解决方法是“Object.freeze({})”。请参阅[参考](https://github.com/facebook/flow/issues/2977#issuecomment-390613203)。 (3认同)