bluepnume
bluepnume

Reputation: 17128

"Possibly undefined value", how to make null safe?

Looking for some help with Facebook's Flow.

I have the following code:

function getValues(obj? : Object) {

    if (obj) {
        return Object.keys(obj).map(key => {
            return obj[key];
        });
    }

    return [];
}

I get the following error with flow version 0.37.0:

65:             return obj[key];
                       ^^^^^^^^ access of computed property/element. Computed property/element cannot be accessed on possibly undefined value
65:             return obj[key];
                       ^^^ undefined

Am I making a mistake here, or should this code be null safe?

Thanks in advance!

Upvotes: 1

Views: 1864

Answers (1)

gcanti
gcanti

Reputation: 1462

Flow is pessimistic about refinements, it considers that every function call could modify obj. As for a fix, you can use a const binding

function getValues(obj?: Object) {
  const o = obj
  return o ?
    Object.keys(o).map(key => o[key]) :
    []
}

Upvotes: 1

Related Questions