简体   繁体   English

流类型中的(a:?string)和(a?:string)有什么区别?

[英]What is the difference between (a: ?string) and (a?: string) in flow type?

What is the difference between a?: string and a: ?string in Flow? Flow中的? a?: stringa: ?string a?: string什么区别?

function concat(a: ?string, b: ?string): string {
}

vs VS

function concat(a?: string, b?: string): string {
}

a: ?string is a Maybe type - actually string | null | void a: ?stringMaybe类型 - 实际上是string | null | void string | null | void string | null | void in this case. 在这种情况下string | null | void

a?: string is an optional property / paramerter - string | void a?: string可选属性 / paramerter - string | void string | void

The difference between them is that maybe type can also be (in addition to the type itself) null or void , and optional parameter only void . 它们之间的区别在于,类型也可以(除了类型本身) nullvoid ,并且可选参数only void

When calling function with optional or maybe parameters function foo(a?: string) or function(a: ?string) - in both cases parameter can be omitted. 当使用可选或可能的参数function foo(a?: string)function(a: ?string)调用函数时 - 在这两种情况下都可以省略参数。

Another difference is in object properties - only optional properties can be omitted: 另一个区别在于对象属性 - 只能省略可选属性:

type WithOptional = {
  foo?: string;
}
type WithMaybe = {
  foo: ?string;
}

const a: WithOptional = {}; // OK
const b: WithMaybe = {}; // Error

a?: string is an optional parameter . a?: string可选参数 From the docs: 来自文档:

Optional parameters will accept missing, undefined , or matching types. 可选参数将接受缺失, undefined或匹配类型。 But they will not accept null . 但他们不会接受null

a: ?string is a maybe type . a: ?string是一种类型 From the docs: 来自文档:

It's common for JavaScript code to introduce “optional” values so that you have the option of leaving out the value or passing null instead. JavaScript代码引入“可选”值是很常见的,这样您就可以选择省略值或传递null。

... ...

Maybe types accept the provided type as well as null or undefined . 也许类型接受提供的类型以及nullundefined So ?number would mean number , null , or undefined . 那么?number表示numbernullundefined

So the chief difference appears to be that you can use null for a maybe type, but not for an optional parameter. 因此,主要区别似乎是您可以对可能的类型使用null ,但不能为可选参数使用null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM