Skip to main content

类型别名

当你想要在多个位置重用复杂类型时,你可以使用类型别名在 Flow 中为它们起别名。

¥When you have complicated types that you want to reuse in multiple places, you can alias them in Flow using a type alias.

1type MyObject = {2  foo: number,3  bar: boolean,4  baz: string,5};

这些类型别名可以在任何可以使用类型的地方使用。

¥These type aliases can be used anywhere a type can be used.

1type MyObject = {2  // ...3};4
5const val: MyObject = { /* ... */ };6function method(val: MyObject) { /* ... */ }7class Foo { constructor(val: MyObject) { /* ... */ } }

类型别名就是这样:别名。他们不会创造一种不同的类型,而只是创造一种类型的另一个名称。这意味着类型别名可以与其等效的类型完全互换。

¥Type aliases are just that: aliases. They don't create a different type, just another name for one. This means that a type alias is completely interchangeable with the type it is equal to.

1type MyNumber = number;2declare const x: MyNumber;3declare function foo(x: number): void;4foo(x); // ok, because MyNumber = number

当你不想将类型视为相同时,不透明类型别名 提供了另一种选择。

¥Opaque type aliases offer an alternative for when you don't want to treat the types as the same.

类型别名语法

¥Type Alias Syntax

类型别名是使用关键字 type 后跟其名称、等号 = 和类型定义创建的。

¥Type aliases are created using the keyword type followed by its name, an equals sign =, and a type definition.

type Alias = Type;

任何类型都可以出现在类型别名中。

¥Any type can appear inside a type alias.

1type NumberAlias = number;2type ObjectAlias = {3  property: string,4  method(): number,5};6type UnionAlias = 1 | 2 | 3;7type AliasAlias = ObjectAlias;

类型别名泛型

¥Type Alias Generics

类型别名也可以有自己的 泛型

¥Type aliases can also have their own generics.

1type MyObject<A, B, C> = {2  property: A,3  method(val: B): C,4};

类型别名泛型是 参数化的。当你使用类型别名时,你需要为其每个泛型传递参数。

¥Type alias generics are parameterized. When you use a type alias you need to pass parameters for each of its generics.

1type MyObject<A, B, C> = {2  foo: A,3  bar: B,4  baz: C,5};6
7var val: MyObject<number, boolean, string> = {8  foo: 1,9  bar: true,10  baz: 'three',11};