alvaromb
alvaromb

Reputation: 4856

How to set a default value for a Flow type?

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.

Upvotes: 20

Views: 25154

Answers (4)

Mazaher Muraj
Mazaher Muraj

Reputation: 2859

If setting it for a component then you can set a default value like so:

type Props = {
  code: number,
  type: number,
}

const Component = (props: Props) => (
  <div>{props.code}</div>
  <div>{props.type}</div>
);

// default values
const defaultProps: Props = {
  code: '',
  type: 1,
};

Component.defaultProps = defaultProps;

export default Component;

Upvotes: 0

Rohman HM
Rohman HM

Reputation: 2827

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

Upvotes: 21

Mark Palange
Mark Palange

Reputation: 61

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.

Upvotes: 6

basarat
basarat

Reputation: 275799

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

Upvotes: 2

Related Questions