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 {
}
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
a?: string
is an optional parameter. From the docs:
Optional parameters will accept missing,
undefined
, or matching types. But they will not acceptnull
.
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
orundefined
. So ?number would meannumber
,null
, orundefined
.
So the chief difference appears to be that you can use null
for a maybe type, but not for an optional parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With