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

如何为可返回两种不同类型对象的函数添加类型注解?

解决Flow中返回两种对象类型的函数类型注解问题

首先看你代码里的核心问题:你定义的MaybeResult联合类型中,{| favoriteFruit: void |}这部分和实际返回值不匹配——你实际返回的是favoriteFruit: 'apple'(字符串类型),但void在Flow里表示该属性的值为undefined或者这个属性不存在,这直接导致了类型校验失败。

下面是修正后的完整代码:

// @flow
type MaybeResult = {| err: string |} | {| favoriteFruit: string |};
const getFavoriteFruitObj = (name: string): MaybeResult => 
  name === 'john' ? ({ favoriteFruit: 'apple' }) : ({ err: 'I only know peter\'s favorite fruit!' });

顺便补充几个关键细节:

  • 别忘了给参数name加上string类型注解,Flow才能完整校验输入参数的合法性,避免隐式类型问题。
  • 你用的精确对象类型({| |})写法是正确的,这种语法能严格限定对象只能包含你声明的属性,防止额外的隐式属性破坏类型安全。
  • 如果favoriteFruit的取值是固定的几个选项(比如只有'apple'或'banana'),可以改成更精确的字面量类型,比如{| favoriteFruit: 'apple' | 'banana' |},让Flow做更严格的类型检查。

如果之后要处理这个函数的返回值,可以用类型守卫来区分两种情况,Flow会自动推导分支里的类型:

const result = getFavoriteFruitObj('john');
if ('err' in result) {
  // 这里Flow明确知道result是{ err: string }类型
  console.log(result.err);
} else {
  // 这里Flow明确知道result是{ favoriteFruit: string }类型
  console.log(result.favoriteFruit);
}

这样就能确保整个逻辑的类型安全啦!

内容的提问来源于stack exchange,提问作者Rob Wise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:18:37