You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件Props中Flow泛型未捕获类型错误的原因

Why Flow Isn't Catching Your Generic Type Error

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 fetch prop returns a Promise<number>, so number has to be a subtype of T (since Promise types are covariant—Promise<number> can safely be used where Promise<T> is expected if number is a subset of T).
  • Your cb prop is (number) => string. For this to match T => T, Flow's default behavior (which treats function parameters as bivariant—both covariant and contravariant) allows it to infer T as number | string:
    • The parameter number is a subtype of number | string (covariant parameter check passes).
    • The return value string is a subtype of number | string (covariant return check passes).
    • Promise<number> is also a subtype of Promise<number | string>, so all constraints are satisfied.

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:36:29