Pavel Barmin
Pavel Barmin

Reputation: 63

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

Upvotes: 3

Views: 195

Answers (2)

Pavel Barmin
Pavel Barmin

Reputation: 63

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

Upvotes: 0

Sasha
Sasha

Reputation: 5944

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.

Upvotes: 1

Related Questions