简体   繁体   English

为什么空 object 对流类型中的非精确类型注释有效?

[英]Why empty object is valid for non exact type annotation in flow type?

I mean code like我的意思是像这样的代码

const someObj: { id: number } = {};
const num: number = someObj.id;
console.log(num);

num here is undefined, and definitely not a number这里的num是未定义的,绝对不是数字

Snippet can be checked here https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoAxnAdgZwC5g5wC2ApgPIBGAVgFxgDeYAlgCb1YCuxlpATmAC+YALyNBAbgzZ8YLsQ7deAsUTJVqAOjYSgA片段可以在这里查看https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoAxnAdgZwC5g5wC2ApgPIBGAVgFxgDeYAlgCb1YCuxlpATmAC+YALyNBAbgzZ8YLsQ7deAsUTJVAOjYgS

This is a documented limitation for unsealed objects:这是未密封对象的记录限制

Unsealed objects allow new properties to be written at any time.未密封的对象允许随时写入新属性。 Flow ensures that reads are compatible with writes, but does not ensure that writes happen before reads (in the order of execution). Flow 确保读取与写入兼容,但不确保写入发生在读取之前(按执行顺序)。

This means that reads from unsealed objects with no matching writes are never checked.这意味着从不检查没有匹配写入的未密封对象的读取。 This is an unsafe behavior of Flow which may be improved in the future.这是 Flow 的不安全行为,将来可能会改进。

So normally flow can check that id is written as number, but can not check if id has actually been written to the someObj .因此,通常流可以检查id是否写为数字,但无法检查id是否实际上已写入someObj

Added an issue, there is some discussion about too - https://github.com/facebook/flow/issues/8430添加了一个问题,也有一些讨论 - https://github.com/facebook/flow/issues/8430

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM