What & Why
Setup
Type Annotations
Type System
ConfigurationLibraries
For Potential Contributors
Index

Optional Types

Edit

Sometimes you need to include undefined to defined variable/object property. Optional type is a solution. It is not some separated type. It's special syntax for type that adds to any type additional value - undefined. You can create them by adding a question mark in front of the type name.

Playground
const givenAge = -5;
const userAge: ?number = givenAge > 0 ? givenAge : undefined;

Warning: Unlike Flow.js, Hegel will throw an error if you try to assign null as value of an optional type

Playground
// Error: Type "null" is incompatible with type "number | undefined"
const someValue: ?number = null;

Optional type is not only about undefined variables or object properties. You can use it inside function argument definition to annotate optional argument.

Playground
function doSomething(optionalArg: ?number) {}
doSomething(); // 👌!
doSomething(42); // 👌!
doSomething(undefined); // 👌!
// Error: Type "null" is incompatible with type "number | undefined"
doSomething(null);

Also you can use it inside object type definition to annotate optional property.

Playground
let user: { name: ?string } = { name: "Arya Stark" };
user.name = undefined; // 👌!
user.name = "Arya Stark"; // 👌!
// Error: Type "null" is incompatible with type "number | undefined"
user.name = null;
user = {}; // 👌!
user = { name: "Arya Stark" }; // 👌!
user = { name: undefined }; // 👌!
// Error: Type "{ name: null }" is incompatible with type "{ name: string | undefined }"
user = { name: null };