Flow: Error when exporting a function working with a Map

Created on 17 Nov 2017  路  2Comments  路  Source: facebook/flow

This seems maybe potentially related to https://github.com/facebook/flow/issues/4805 but I'm not entirely sure. You can check out the error at the Try Flow page.

type State = {
  thing: Map<string, boolean>
}

const initialState: State = {
  thing: new Map()
}

const what = (state: State = initialState, {type, payload}) => {
  switch(type) {
    case 'thing':
      return {
        ...state,
        thing: new Map(state.thing)
      }
  }
}

export default what;

results in

16:         thing: new Map(state.thing)                   ^ type parameter `K` of constructor call. Missing annotation
16:         thing: new Map(state.thing)                   ^ type parameter `V` of constructor call. Missing annotation

If you comment out the export default line, you will see that it stops complaining about the missing annotation for K and V.

I can guess that it wants me to annotate the types for some reason (even though it's already declared?) but I have no idea what this syntax is supposed to be.

Most helpful comment

Your example is missing return type and a default case for switch to eliminate undefined.

This type checks (Try Flow):

/* @flow */

type State = {
  thing: Map<string, boolean>
}

const initialState: State = {
  thing: new Map()
}

const what = (state: State = initialState, {type, payload}: Object): State => {
  switch(type) {
    case 'thing':
      return {
        ...state,
        thing: new Map(state.thing)
      }
    default:
      return state;
  }
}

export default what;

I agree that the error message is cryptic. The rule of thumb here I think is always make sure the return type is there for exported functions.

All 2 comments

Your example is missing return type and a default case for switch to eliminate undefined.

This type checks (Try Flow):

/* @flow */

type State = {
  thing: Map<string, boolean>
}

const initialState: State = {
  thing: new Map()
}

const what = (state: State = initialState, {type, payload}: Object): State => {
  switch(type) {
    case 'thing':
      return {
        ...state,
        thing: new Map(state.thing)
      }
    default:
      return state;
  }
}

export default what;

I agree that the error message is cryptic. The rule of thumb here I think is always make sure the return type is there for exported functions.

Oh wow, I never would've thought of that from that error message. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamiebuilds picture jamiebuilds  路  3Comments

glenjamin picture glenjamin  路  3Comments

philikon picture philikon  路  3Comments

mmollaverdi picture mmollaverdi  路  3Comments

cubika picture cubika  路  3Comments