dumbmatter
dumbmatter

Reputation: 9663

What does Flow not like about this code that conditionally accesses an object's property only if it exists

Here's my code:

// @flow

var x = {a: 'foo'};
var key = Math.random() > 0.5 ? 'b' : 'a';
var value = x.hasOwnProperty(key) ? x[key] : 'default';
console.log(value);

So x[key] is only accessed if key really is a property of x, otherwise a default value is used. But Flow does not like this, it says:

test-flow.js:5
  5: var value = x.hasOwnProperty(key) ? x[key] : 'default';
                                           ^^^ property `b`. Property not found in
  5: var value = x.hasOwnProperty(key) ? x[key] : 'default';
                                         ^ object literal

Any idea what I'm doing wrong?

Upvotes: 3

Views: 562

Answers (1)

Nikita
Nikita

Reputation: 2943

This looks like a bug in Flow. You might want to open an issue on their github.

Meanwhile, adding an explicit type to key fixes the problem for some reason:

var key: string = ...

Upvotes: 4

Related Questions