How to set a default value for a Flow type?

amb picture amb · Sep 28, 2016 · Viewed 20.4k times · Source

I have defined a custom Flow type

export type MyType = {
  code: number,
  type: number = 1,
}

I want the type parameter to default as 1 if no value is present. However, Flow is complaining with Unexpected token =.

Flow error

Can this be done with Flow?

Currently using Flow v0.32.0.

Answer

Rohman Masyhar picture Rohman Masyhar · Apr 27, 2017

Function parameters can also have defaults. This is a feature of ECMAScript 2015.

function method(value: string = "default") { /* ... */ }

In addition to their set type, default parameters can also be void or omitted altogether. However, they cannot be null.

// @flow
function acceptsOptionalString(value: string = "foo") {
  // ...
}

acceptsOptionalString("bar");
acceptsOptionalString(undefined);
acceptsOptionalString(null);
acceptsOptionalString();

https://flow.org/en/docs/types/primitives/#toc-function-parameters-with-defaults