Type alias in flow with brackets and ellipsis

杀马特。学长 韩版系。学妹 提交于 2020-06-28 05:47:27

问题


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?


回答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/



来源:https://stackoverflow.com/questions/62353038/type-alias-in-flow-with-brackets-and-ellipsis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!