流类型问号? [英] flow type question mark?
问题描述
对使用'?'感到困惑在流动. AFAIK(要感谢流类型问号在参数之前还是之后?):
So confused on using '?' in flow. AFAIK (thanks to flow type question mark before or after param?):
-
何时为'?'在':'之前,表示bar是可选的,可以是字符串或未定义:
bar?: string
When '?' before ':', means bar is optional, can be string or undefined:
bar?: string
何时为'?'在':'之后,表示bar可能是类型,可以是字符串,未定义或null.
bar: ?string
When '?' after ':', means bar is maybe type, can be string, undefined, or null.
bar: ?string
我的问题是:在哪种情况下,第一种选择应该优先于第二种选择? bar?: ?string
怎么样?
My question is: In which circumstance we should the first option over the second? How about bar?: ?string
?
流很难...
推荐答案
可选表示该属性可以省略.看这个例子:
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
关于可选和可能的组合-允许将null
分配给可选属性:
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
这篇关于流类型问号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!