Flow类型中(a: ?string)与(a?: string)的区别是什么?
(a: ?string) vs (a?: string) — What’s the Difference? Great question! Let’s break down the critical differences between these two Flow syntax patterns, using your exact concat function examples to make things crystal clear.
Core Definitions
First, let’s clarify what each syntax actually means:
a: ?string(Nullable Type): This tells Flow that the parameter must be provided when calling the function, but its value can be astring,null, orundefined. You can’t skip passing this parameter entirely—you have to send something, even if it’snullorundefined.a?: string(Optional Parameter): This means the parameter can be omitted from the function call. If you do pass a value, it has to be astring; if you skip it, the parameter will beundefinedinside the function.nullisn’t allowed here unless you explicitly add it to the type.
Behavior in Your concat Examples
Let’s map this to your two function declarations:
Function 1: function concat(a: ?string, b: ?string): string { }
This function requires both arguments every time you call it—no exceptions. The only flexibility is that each argument can be a string, null, or undefined.
- ✅ Valid calls:
concat("hello", "world"); // Both strings concat(null, undefined); // Nullable values are allowed concat("foo", null); // Mix of string and null - ❌ Invalid calls (Flow will throw errors):
concat("hello"); // Missing the second argument `b` concat(); // Missing both arguments entirely
Function 2: function concat(a?: string, b?: string): string { }
This function lets you call it with 0, 1, or 2 arguments. But any value you do pass has to be a proper string—no null allowed by default.
- ✅ Valid calls:
concat(); // No arguments, both params are undefined concat("hello"); // Only first argument provided concat("hello", "world"); // Both strings - ❌ Invalid calls (Flow will throw errors):
concat(null, "world"); // `null` isn't a string type concat(undefined, null); // `null` isn't allowed for `b`
Want the Best of Both Worlds?
If you need a parameter that’s optional (can be skipped) and accepts null/undefined when provided, combine the two syntaxes:
function concat(a?: ?string, b?: ?string): string { }
Now you can call concat(), concat(null), or concat("foo", undefined)—all will pass Flow’s checks.
内容的提问来源于stack exchange,提问作者Rohan

