Flow: Computed properties - expecting a flow error, but there is none.

Created on 1 Dec 2016  路  9Comments  路  Source: facebook/flow

I'm trying to type check a computed property and was expecting an error but am not seeing one.

function create(key: string): {[key:string]: number} {
  return {
      [key]: 'Not a number' // Does not cause a flow error
  }
}

Try Flow Link

Is it possible to enforce the {[key:string]:number} type when using computed properties?

Thanks.

object model bug

Most helpful comment

Yup. Will fix.

All 9 comments

Oh weird! That's definitely a bug! I'll check in with @samwgoldman and we'll get this fixed. Thanks for the report!

Oh I think I see what's happening. Since Flow doesn't know the exact value of key, I'm guessing the type of the object literal doesn't reflect the computed prop. If you change the code to

function create(key: 'foo'): {[key:string]: number} {
  return {
      [key]: 'Not a number' // Now causes an error
  }
}

now it causes an error, since Flow knows the value of key and the object type now contains a property foo with the type string.

I suppose the solution will be to automatically create an indexer for object properties when they have unknown computed properties, or something like that!

Yup. Will fix.

Just wondering if this is on the roadmap anytime soon?
Obviously you're providing this tool to the community for free (and it's a fantastic tool), so don't want to seem too ungrateful. I haven't used OCaml before, but if you could point out where and what needs to be done, I could make an attempt at it.
Thanks.

This would be a lovely fix to have. My use case is that of using Redux, where using computed keys is very common in reducers. This bug prevents meaningful type safety on the shape of the store.

type State = {
    byId: {
        [id:number]: { id: number, foo: string }
    }
}

type Action = {
    payload: { id: number, bar: string }
}

function myReducer(state: State, action: Action): State {
    return {
        ...state,
        byId: {
            ...state.byId,
            [action.payload.id]: action.payload, // <-- Expected type mismatch
        }
    }
}

I am also facing this issue, it would be nice to have a fix soon :)

I've been bitten by this a few times now.

@samwgoldman @gcanti Any update on this? It's still an issue, and especially painful for those of us using redux. Does Flow have product pains or similar so we can upvote this issue? 馃檹 There is also no easy workaround afaik.

Was this page helpful?
0 / 5 - 0 ratings