React组件Props中Flow泛型未捕获类型错误的原因
Let me break down why you're not seeing the expected type error, and how to fix it.
The Root Cause
Flow's type inference is designed to find the widest possible type T that satisfies all your generic constraints. In your code, here's what's happening:
- Your
fetchprop returns aPromise<number>, sonumberhas to be a subtype ofT(since Promise types are covariant—Promise<number>can safely be used wherePromise<T>is expected ifnumberis a subset ofT). - Your
cbprop is(number) => string. For this to matchT => T, Flow's default behavior (which treats function parameters as bivariant—both covariant and contravariant) allows it to inferTasnumber | string:- The parameter
numberis a subtype ofnumber | string(covariant parameter check passes). - The return value
stringis a subtype ofnumber | string(covariant return check passes). Promise<number>is also a subtype ofPromise<number | string>, so all constraints are satisfied.
- The parameter
Because Flow finds a valid T (number | string) that works for both props, it doesn't throw an error—even though this isn't the strict type match you intended.
Fixes to Enforce Strict Typing
1. Explicitly Specify the Generic Type
The simplest fix is to tell Flow exactly what T should be when you use your component or function. This overrides its default wide inference:
React Component Example
const App = () => ( <Client<number> fetch={ () => Promise.resolve(1) } cb={ n => 'sfd' } /> );
Regular Function Example
fun<number>(() => 2, n => 'qwe');
Now Flow will immediately flag the error, since cb returns a string instead of the expected number.
2. Enable Strict Function Parameter Checking
If you want Flow to enforce strict contravariant checking for function parameters (the correct behavior for type safety), add this to your .flowconfig:
[strict] function_parameters = true
With this setting, Flow will no longer allow bivariant parameter checks. In your original code, it will detect that there's no valid T that can satisfy both fetch returning number and cb returning string, and throw the expected error.
内容的提问来源于stack exchange,提问作者Sam R.

