flow type question mark?

问题: So confused on using '?' in flow. AFAIK (thanks to flow type question mark before or after param?): When '?' before ':', means bar is optional, can be string or undef...

问题:

So confused on using '?' in flow. AFAIK (thanks to flow type question mark before or after param?):

  1. When '?' before ':', means bar is optional, can be string or undefined: bar?: string

  2. When '?' after ':', means bar is maybe type, can be string, undefined, or null. bar: ?string

My question is: In which circumstance we should the first option over the second? How about bar?: ?string ?

flow is hard...


回答1:

Optional means that the property can be omitted. Have a look at this example:

type Foo = {
  optional?: string
}

const foo: Foo = {}; // OK

type Bar = {
  maybe: ?string;
}

const bar: Bar = {}; // Error: `maybe` is missing in object literal

Regarding combination of optional and maybe - it allows assigning null to optional property:

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
  • 发表于 2018-07-06 02:12
  • 阅读 ( 51 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除