Type Aliases

Aliasing types for reuse

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

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

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

1
2
3
4
5
6
7
8
// @flow
type MyObject = {
  // ...
};

var val: MyObject = { /* ... */ };
function method(val: MyObject) { /* ... */ }
class Foo { constructor(val: MyObject) { /* ... */ } }

Type Alias Syntax

Interfaces are created using the keyword type followed by it’s name, an equals sign =, and a type definition.

1
type Alias = Type;

Any type can appear inside a type alias.

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

Type Alias Generics

Type aliases can also have their own generics.

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

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

1
2
3
4
5
6
7
8
9
10
11
12
// @flow
type MyObject<A, B, C> = {
  foo: A,
  bar: B,
  baz: C,
};

var val: MyObject<number, boolean, string> = {
  foo: 1,
  bar: true,
  baz: 'three',
};