流式问号?

nic*_*ayi 4 javascript flowtype

使用'?'时很困惑 在流动中.AFAIK(感谢param之前或之后的流式问号?):

  1. 什么时候 '?' 在':'之前,表示bar是可选的,可以是字符串或未定义: bar?: string

  2. 什么时候 '?' 在':'之后,表示bar可能是type,可以是string,undefined或null. bar: ?string

我的问题是:在哪种情况下,我们应该在第二种情况下选择第一种方案?怎么样bar?: ?string

流很难......

Ale*_* L. 6

可选意味着可以省略属性.看看这个例子:

type Foo = {
  optional?: string
}

const foo: Foo = {}; // OK

type Bar = {
  maybe: ?string;
}

const bar: Bar = {}; // Error: `maybe` is missing in object literal
Run Code Online (Sandbox Code Playgroud)

关于可选和可能的组合 - 它允许分配null给可选属性:

type Baz = {
  maybeAndOptional?: ?string;
}

let baz: Baz = {}; // OK
baz = { maybeAndOptional: null }; // OK

type Foo = {
  optional?: string
}

let foo: Foo = {}; // OK
foo = { optional: null } // Error: null is incompatible with string
Run Code Online (Sandbox Code Playgroud)