Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between (a: ?string) and (a?: string) in flow type?

What is the difference between a?: string and a: ?string in Flow?

function concat(a: ?string, b: ?string): string {
}

vs

function concat(a?: string, b?: string): string {
}
like image 629
Rohan Avatar asked May 01 '18 06:05

Rohan


2 Answers

a: ?string is a Maybe type - actually string | null | void in this case.

a?: string is an optional property/paramerter - string | void

The difference between them is that maybe type can also be (in addition to the type itself) null or void, and optional parameter only void.

When calling function with optional or maybe parameters function foo(a?: string) or function(a: ?string) - in both cases parameter can be omitted.

Another difference is in object properties - only optional properties can be omitted:

type WithOptional = {
  foo?: string;
}
type WithMaybe = {
  foo: ?string;
}

const a: WithOptional = {}; // OK
const b: WithMaybe = {}; // Error
like image 92
Aleksey L. Avatar answered Nov 14 '22 23:11

Aleksey L.


a?: string is an optional parameter. From the docs:

Optional parameters will accept missing, undefined, or matching types. But they will not accept null.

a: ?string is a maybe type. From the docs:

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.

...

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

So the chief difference appears to be that you can use null for a maybe type, but not for an optional parameter.

like image 21
T.J. Crowder Avatar answered Nov 14 '22 21:11

T.J. Crowder