Maybe Types

Maybe Types

It’s common for JavaScript code to introduce “optional” values so that you have the option of leaving out the value or passing null instead.

Using Flow you can use Maybe types for these values. Maybe types work with any other type by simply prefixing it with a question mark ? such as ?number as a sort of modifier.

Maybe types accept the provided type as well as null or undefined. So ?number would mean number, null, or undefined.

// @flow
function acceptsMaybeNumber(value: ?number) {
  // ...
}

acceptsMaybeNumber(42);        // Works!
acceptsMaybeNumber();          // Works!
acceptsMaybeNumber(undefined); // Works!
acceptsMaybeNumber(null);      // Works!
acceptsMaybeNumber("42");      // Error!

Refining Maybe types

Imagine we have the type ?number, if we want to use that value as a number we’ll need to first check that it is not null or undefined.

// @flow
function acceptsMaybeNumber(value: ?number) {
  if (value !== null && value !== undefined) {
    return value * 2;
  }
}

You can simplify the two checks against null and undefined using a single != null check which will do both.

// @flow
function acceptsMaybeNumber(value: ?number) {
  if (value != null) {
    return value * 2;
  }
}

You could also flip it around, and check to make sure that the value has a type of number before using it.

// @flow
function acceptsMaybeNumber(value: ?number) {
  if (typeof value === 'number') {
    return value * 2;
  }
}

© 2013–present Facebook Inc.
Licensed under the BSD License.
https://flow.org/en/docs/types/maybe

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部