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

Flow中匹配的联合类型为何不等价?如何修复相关报错?

Flow联合类型赋值错误的解决方法

从测试来看,Flow似乎只能在顶层检查联合类型的等价性。我想知道修复这个错误的方法,最好不用覆盖联合类型所有分支的switch语句。

问题代码

type BadRequest = {| __typename: 'BadRequest' |} 
type Forbidden = {| __typename: 'Forbidden' |}

type EitherObject = BadRequest | Forbidden
type EitherLiteral = "BadRequest" | "Forbidden"

const eitherLiteral: EitherLiteral = "BadRequest"

const eitherObject: EitherObject = {__typename: eitherLiteral} // Error?

解决方法

方案一:类型断言

直接用类型断言明确告知Flow该对象符合目标类型要求:

const eitherObject: EitherObject = {__typename: eitherLiteral} as EitherObject;

方案二:轻量类型转换函数

如果需要更严谨的类型保障,可以定义一个无需遍历所有分支的转换函数:

function toEitherObject(type: EitherLiteral): EitherObject {
  return { __typename: type } as $Exact<{ __typename: typeof type }>;
}

const eitherObject: EitherObject = toEitherObject(eitherLiteral);

这里$Exact用于确保对象结构完全匹配联合类型的成员,Flow会自动识别typeof type与对应分支的__typename等价,从而通过类型检查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:35:45