Type Aliases
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 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};