Search code examples
javascriptreactjsflowtype

How to fix Flow error when accessing a field with default value on an object?


Example

Flow REPL

Problem

I'm trying to access a field on an object that I believe should always exist.

How can the following flow error be resolved?

Snippet

problem = (arg: {refKey: string} = {}) => {
  const {refKey = 'ref', ...rest} = arg;
  return {
    [refKey]:arg[refKey],
    ...rest
  };
};

Error:

19:       [refKey]:arg[refKey],
                       ^ Cannot get `arg[refKey]` because property `ref` is missing in object type [1].
References:
16:   problem = (arg: {refKey: string} = {}) => {
                      ^ [1]

Solution

  • It's happening because you are setting the value when you are declaring it.

    If you want to set a default value, you can set it in the default parameter, like so:

    problem = (arg: {refKey: string} = {refKey: 'ref'}) => {
      const {refKey, ...rest} = arg;
      return {
        [refKey]:arg[refKey],
        ...rest
      };
    };
    

    EDIT

    Okay, I think I misunderstood the problem and have now understood it (!).

    If the default property will be named 'ref', you can do this:

    problem = (arg: {refKey: string, ref: any} = {}) => {
      const {refKey = 'ref', ...rest} = arg;
      return {
        [refKey]:arg[refKey],
        ...rest
      };
    };