Javascript 对象文字。不精确类型与精确类型不兼容(无对象排列)
在以下情况下,Flow可以正确使用精确类型:Javascript 对象文字。不精确类型与精确类型不兼容(无对象排列),javascript,flowtype,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}; // --------||--------- ……
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
这与不使用差价的情况不同
使用最新的
0.57.3
测试,无属性的对象
文本被推断为流中未密封的对象类型,也就是说,您可以向此类对象添加属性或解构不存在的属性,而不会引发错误:
// 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
要将空对象
文本作为不带属性的确切类型键入,需要显式密封它:
type Empty = {||};
const o :Empty = Object.seal({}); // type checks
请注意,
密封件
不再起作用。当前的解决方法是Object.freeze({})
。看见