对使用“?”感到困惑在流动中。据我所知(感谢参数之前或之后的流类型问号? https://stackoverflow.com/questions/47314749/flow-type-question-mark-before-or-after-param):
什么时候 '?'在 ':' 之前,表示 bar 是可选的,可以是字符串或未定义:
bar?: string
什么时候 '?' ':' 之后,表示 bar 可能是类型,可以是字符串、未定义或 null。
bar: ?string
我的问题是:在什么情况下我们应该选择第一个而不是第二个?怎么样bar?: ?string
?
流量好难...
可选意味着该属性可以省略。看看这个例子:
type Foo = {
optional?: string
}
const foo: Foo = {}; // OK
type Bar = {
maybe: ?string;
}
const bar: Bar = {}; // Error: `maybe` is missing in object literal
关于可选和也许的组合 - 它允许分配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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)