Flow: Empty object is valid for non exact type annotation

Created on 4 Jul 2020  路  7Comments  路  Source: facebook/flow

Flow version: 0.128.0

Expected behavior

Type error

Actual behavior

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

num here is undefined, and definitely not a number

bug needs triage unsealed objects

Most helpful comment

Agreed. We have wanted to get rid of unsealed objects for a while, the difficulty is devising a new way to support the existing pattern of building up an object over time.

All 7 comments

This is just how unsealed objects work in Flow.

@jcready How is this related to sealed/unsealed if the type is explicitly specified? Also if it would be unsealed the following would be allowed:

const someObj: { id: number } = {};
someObj.foo = 'foo';

but it is not https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoAxnAdgZwC5g5wC2ApgPIBGAVgFxgDeYAlgCb1YCuxlpATmAC+YALyNBAblREyVagDoocOKLAByJXDUSgA

Annotating the type of someObj limits what you can do with it. When initializing someObj, you write an unsealed object to the variable, but then tell Flow you only want to allow it to be used as if it is a value of type {id : number}. So the unsealedness of the empty object literal is masked by the fact that you are immediately annotating the value you are assigning it to.

Thanks @dsainati1 this makes it clearer. (I still feel like it is not desired behavior)

Agreed. We have wanted to get rid of unsealed objects for a while, the difficulty is devising a new way to support the existing pattern of building up an object over time.

See #7424

Was this page helpful?
0 / 5 - 0 ratings