'Type alias in flow with brackets and ellipsis

type WeirdCustomType = {[int]: boolean, ...};

What kind of structure is WeirdCustomType? Is it simply an array of {int:boolean} types ? (ie, key is an int, value is a boolean)? If so, what is the meaning of ... here? And where can I read about this particular type aliasing usage?



Solution 1:[1]

WeirdCustomType is an “Explicit inexact object type

Its properties consist of:

  • A) properties with integer keys with boolean values
    • the brackets around int indicate that we’re referring to the property keys, and that those keys are of type int (which should actually be number, see last section of my answer)
    • this follows destructuring syntax for objects and their keys, and you can read more about “Computed object property names and destructuring” on the MDN docs
  • B) additional properties with other keys and value types

Here’s how an object of WeirdCustomType may look:

const inexactObject: WeirdObjectType = {
  1: ‘foo’,
  2: ‘bar’,
  baz: ‘abc’
}

The ellipses on WeirdCustomType indicate explicitly (to make it extra clear) that this type allows for an object with extra properties where a normal object type is expected.

To disable that behavior, you can use the exact object type. As described in the documentation,

Unlike regular object types, it is not valid to pass an object with “extra” properties to an exact object type.

// @flow
var foo: {| foo: string |} = { foo: "Hello", bar: "World!" }; // Error!

Here’s a post on Medium that explains the motivation.

Currently, {foo: number} is the type for any object which has a property foo with type number. {| foo: number |} is the type for an object which ONLY has a property foo with type number. We say the former syntax is an inexact object and the latter is an exact object.

In a few releases, Flow will begin to treat {foo: number} as an exact object. To indicate inexactness, you must add an ellipsis to the end of an object type: {foo: number, ...}. This new syntax forces the developers to opt in to inexactness.

note on int type

Flow doesn’t actually have a primitive type int. Integers are represented by the number type. I believe that the [int] should be [number].

See https://flow.org/en/docs/types/primitives/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community