34

Can someone explain the difference between:

function foo(bar: ?string) {
  console.log(bar);
}

and:

function foo(bar?: string) {
  console.log(bar);
}

When to use one over the other?

1

2 Answers 2

46

Basically

bar: ?string

accepts a string, null or void:

foo("test");
foo(null);
foo()

While

bar?: string

Accepts only a string or void:

foo("test");
foo();

As passing null instead of a string is somewhat senseless, theres no real life difference between them.

7
  • 2
    I've seen bar?: ?string somewhere, when would you use that? Or does that make no sense?
    – Tieme
    Aug 13, 2018 at 14:14
  • 1
    @tieme no that makes no sense (at least not to me) :) Aug 13, 2018 at 14:22
  • Check. And inside an object literal? type Styles = { fontName?: ?string; }
    – Tieme
    Aug 13, 2018 at 15:49
  • 1
    It's explained pretty clearly here: flow.org/en/docs/types/maybe Sep 21, 2018 at 7:09
  • 2
    @BradPeabody according to the docs { prop?: foo } is the "optional property syntax" which I'm guessing is a specific usage of the maybe syntax May 20, 2019 at 2:30
13

?string (maybe type) means that bar property can be string aswell as null and void.

bar? means that this property is optional.

More info: https://flow.org/en/docs/types/primitives/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.