flow type question mark before or after param?

Vic picture Vic · Nov 15, 2017 · Viewed 8.4k times · Source

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?

Answer

Jonas Wilms picture Jonas Wilms · Nov 15, 2017

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.