简体   繁体   中英

Flowtype error when trying to get object value via dynamic key

I have a code that receives an object, iterates its keys and performs different actions based on particular key presence in another config object.

Here's an abstract example:

type InputObject = {
  foo: number,
  bar: number,
  baz: number,
};

const multipliers = {
  bar: 3,
};

function processData(data: InputObject) {
  Object.keys(data).forEach(key => {
    const value = data[key];

    if (Object.keys(multipliers).indexOf(key) !== -1) {
      console.log(value * multipliers[key]);
    } else {
      console.log(value);
    }
  });
}

If I check this code with flow check command it gives the following errors:

Cannot get multipliers[key] because:
• property baz is missing in object literal [1].
• property foo is missing in object literal [1].

Why Flow doesn't understand that multipliers[key] is executed only if key exists in multipliers ? Is there any way to fix the errors by changing type annotations without changing the code?

Flow is correct in that your object of type InputObject has three required fields vs multipliers has just one field bar. The key is referring to a key of type InputObject. One way is to cast key as a new string and use that as a reference to lookup. This does however make flow lose reference to key's type which is why $Keys<InputObject> makes sense to ensure stronger typing.

type InputObject = {
  foo: number,
  bar: number,
  baz: number
}

const multipliers = {
  bar: 3,
}

function processData(data: inputObject) {
  Object.keys(data).forEach(key: $Keys<InputObject> => {
    const value = data[key];
    const lookupKey = String(key);
    if (multipliers.hasOwnProperty(lookupKey)) {
      console.log(value * multipliers[lookupKey]);
    else {
      console.log(value);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM