简体   繁体   中英

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

Snippet can be checked here https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoAxnAdgZwC5g5wC2ApgPIBGAVgFxgDeYAlgCb1YCuxlpATmAC+YALyNBAbgzZ8YLsQ7deAsUTJVqAOjYSgA

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).

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.

So normally flow can check that id is written as number, but can not check if id has actually been written to the someObj .

Added an issue, there is some discussion about too - https://github.com/facebook/flow/issues/8430

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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