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

为React组件状态赋值枚举类型时出现TypeScript错误

TypeScript + React 枚举分组类型在组件state中的类型兼容问题

问题现象

我定义了枚举Fruits,用StoneFruit和CitrusFruit两个联合类型对枚举值做了分组,把这两个类型用到React组件的状态类型FruitState里时,出现了TypeScript错误:

Type Fruits is not assignable to type StoneFruit

详细错误信息:

TS2416: Property state in type Fruit is not assignable to the same property in base type Component<any, FruitState, any>
Type { one: Fruits; two: Fruits; } is not assignable to type Readonly<FruitState>
Types of property one are incompatible.
Type Fruits is not assignable to type StoneFruit

问题代码

import React from "react"

enum Fruits {
  Orange,
  Lemon,
  Peach,
  Plum
}

type StoneFruit = Fruits.Peach | Fruits.Plum
type CitrusFruit = Fruits.Orange | Fruits.Lemon

type FruitState = {
  one: StoneFruit
  two: CitrusFruit
}
class Fruit extends React.Component<any, FruitState> {
  state = {
    one: Fruits.Peach,
    two: Fruits.Orange
  }
}

const testState: FruitState = {
  one: Fruits.Peach,
  two: Fruits.Orange
}

解决方法

给state显式指定类型为FruitState,错误就消失了:

state: FruitState = {
    one: Fruits.Peach,
    two: Fruits.Orange
  }

原因说明

TypeScript推断类属性类型时,会把Fruits.Peach这类枚举成员的类型推断成整个Fruits枚举类型,而不是精确到单个枚举成员。但FruitState里的one要求是更窄的StoneFruit(只能是Peach或Plum),宽泛的Fruits类型不符合这个严格的类型约束,所以报错。

而显式指定state的类型为FruitState后,TypeScript会直接校验赋值内容是否符合该类型,这时Fruits.Peach会被识别为StoneFruit的合法值,不会再被推断成宽泛的枚举类型,自然就兼容了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:52:39