Flow: Exact object types shouldn't allow indexer properties

Created on 9 Jan 2017  路  5Comments  路  Source: facebook/flow

This doesn't make any sense, it should be an error:

{| [prop: string]: boolean |}
object model

Most helpful comment

There are some cases where exact types together with indexer property makes sense:

For example in this case

// @flow

type AllowedKeys = 'one' | 'two'

type MyObj = $Exact<{
  [key: AllowedKeys]: mixed
}>

const a: MyObj = {
  one: 1,
  two: 3
}

In this example I want object keys exactly match AllowedKeys

All 5 comments

There are some cases where exact types together with indexer property makes sense:

For example in this case

// @flow

type AllowedKeys = 'one' | 'two'

type MyObj = $Exact<{
  [key: AllowedKeys]: mixed
}>

const a: MyObj = {
  one: 1,
  two: 3
}

In this example I want object keys exactly match AllowedKeys

@anru but this example doesn't work, I just pasted it in here:

https://flow.org/try/#0PTAEAEDMBsHsHcBQiAuBPADgU1AQWnPFgCYDSWaAzqALygDksAdlvaAD4Mryz3LrZQAWTQB5AEYArWqAAkAUQAeAQwDGKADwBvRKFABtANYUAXHgIIS5KgF0zAWwCWikogC+APmSrmlFKGUzEQlpOh09ZiwzAEYAGl1QblgzAGZ3IA

I would love it to work, though.

Another workaround for the broken indexer in an exact type {| [AllowedKeys] |}:

type MyObj<T> = {|
    one: T,
    two: T
|}

type AllowedKeys = $Keys<MyObj<*>>

const a: MyObj<*> = {
    one: 1,
    two: 1,
}

See on Try Flow.

BTW, if anyone knows how to get this problem solved with $Call, would be cool if you share :)

I have another use case where we want to allow an object with only one user-defined property. This is represented in JSONSchema as this:

{
  "type": "object",
  "maxProperties": 1,
  "minProperties": 1,
  "patternProperties": {
    "^\\w+$": {
      "type": "string"
    }
  }
}

It kind of makes sense for flow to allow the above to be represented as how the OP suggests:

type SinglePropOnly = {| [string]: string |};
Was this page helpful?
0 / 5 - 0 ratings