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

Flow类型对看似无关的类型抛出错误的技术咨询

Fixing Flow Type Error in Your getMax Function

Hey there! Let's tackle that Flow type error in your getMax function. The root issue is that Flow isn't fully narrowing down the type of b.value inside the reduce callback when dealing with the union of SquareState and InternalSquare—even though you're checking for null, it still sees a potential type mismatch in the Math.max call.

Here's a cleaned-up, error-free version of your code:

type SquareState = { value: number, };
type InternalSquare = { value: number | null, };

export function getMax(squares: Array<InternalSquare> | Array<SquareState>): number {
  return squares.reduce((a, b) => {
    const currentValue = b.value;
    // Flow will automatically narrow currentValue to number here
    return currentValue !== null ? Math.max(a, currentValue) : a;
  }, 0);
}

What changed and why?

  • We removed the explicit type annotations for the reduce callback parameters—Flow can infer them perfectly from the function's input type, which keeps the code cleaner.
  • By extracting b.value to currentValue and checking currentValue !== null, we give Flow a clear signal that when we call Math.max, currentValue is definitely a number (either from SquareState where it's never null, or from InternalSquare where we've ruled out null). This eliminates the type mismatch error.

If you prefer to keep explicit type annotations for clarity, this version works too:

type SquareState = { value: number, };
type InternalSquare = { value: number | null, };

export function getMax(squares: Array<InternalSquare> | Array<SquareState>): number {
  return squares.reduce((a: number, b: InternalSquare | SquareState): number => {
    const currentValue = b.value;
    return currentValue !== null ? Math.max(a, currentValue) : a;
  }, 0);
}

内容的提问来源于stack exchange,提问作者Timothy Jones

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:12:39