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
reducecallback parameters—Flow can infer them perfectly from the function's input type, which keeps the code cleaner. - By extracting
b.valuetocurrentValueand checkingcurrentValue !== null, we give Flow a clear signal that when we callMath.max,currentValueis definitely anumber(either fromSquareStatewhere it's never null, or fromInternalSquarewhere 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
相关产品推荐
相关产品推荐

