Flow: `Object.keys()` should always return 'Array<string>'

Created on 18 Oct 2016  路  5Comments  路  Source: facebook/flow

I'm not sure why, but Flow allows this:

const obj = {
  foo: 1,
  bar: 1,
  baz: 1
};

const obj2: { foo: number, bar: number } = obj;

const keys: Array<'foo'| 'bar'> = Object.keys(obj2);

Instead, it should always be Array<string> unless argument is exact.

object model soundness bug

Most helpful comment

@notadrill the problem here is that at runtime, keys is ["foo", "bar", "baz"]. I agree we need to make Object.keys only return a union of the keys for exact objects, and summarize otherwise.

cc @samwgoldman

All 5 comments

It looks like flow is doing what you suggested. You are telling flow that the type for obj2 is an object with 2 enumerable keys: foo and bar. So based on the type information, Object.keys(obj2) is an array where each item must be "foo" or "bar". The "exact" argument is an enumeration of the two keys, hence Array<'foo' | 'bar'> is the exact type. If you are looking at obj, you've already erased the type information of the baz:1 field in the assignment.

@notadrill the problem here is that at runtime, keys is ["foo", "bar", "baz"]. I agree we need to make Object.keys only return a union of the keys for exact objects, and summarize otherwise.

cc @samwgoldman

Another example:

var x: {} = { foo: 1 };
const keys: Array<number> = Object.keys(x);
keys[0].toFixed();

Yeah, Object.keys is unsound. We added support for keys before we realized how unsound it was. The unsoundness is why Object.values/entries have broad types, and the fix proposed in #2174 will also work for O.keys.

I'm here for unrelated reasons but have to note my amusement that flow has sound return types for Object.values and unsound returns for Object.keys, whereas TypeScript has the exact opposite.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ctrlplusb picture ctrlplusb  路  3Comments

Beingbook picture Beingbook  路  3Comments

bennoleslie picture bennoleslie  路  3Comments

mmollaverdi picture mmollaverdi  路  3Comments

cubika picture cubika  路  3Comments