How to set a default value for a Flow type?

22,832

Solution 1

You cannot have defaults in a type declaration.

Possible idea

Use a class and initialise any defaults using property initialisers : https://basarat.gitbooks.io/typescript/content/docs/classes.html#property-initializer

Solution 2

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

Solution 3

Go with the idea @basarat proposes, and use a class. A class exists as both a type and a value.

The value can be initialized. Flow recognizes a proposed property initializer syntax, so using Flow (for types) and babel (for proposed feature support) you can declare your class like this:

// @flow
export class MyType {
  code: number;
  type: number = 1; 
};

Flow, and the types it lets you define, are not present in the javascript runtime. Thats why type declarations don't support value initializers.

Share:
22,832
amb
Author by

amb

Mobile Tech Lead at apsl.net

Updated on September 17, 2020

Comments

  • amb
    amb over 3 years

    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.