我有用类型构建的枚举和枚举组.当我使用enum组(在本例中是StoneFruit和CitrusFruit)来输入组件的状态时,我会出现类型脚本错误.但错误消息对我来说绝对没有意义

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 = {
    one: Fruits.Peach,
    two: Fruits.Orange
  }

推荐答案

当您没有显式指定属性的类型时,TS会推断这些值可以容纳的最简单的类型,在您的情况下是Fruits.这被称为document中提到的最佳常见类型

在您的情况下:

state = {
  one: Fruits.Peach,  // TypeScript infers this as Fruits
  two: Fruits.Orange  // TypeScript infers this as Fruits
}

然后,由于TS使用structural type system,因此 struct {one: Fruits; two: Fruits;}不适合FruitState.正如您已经做过的那样,解决方案是显式state的类型

Reactjs相关问答推荐

Redux向后端发送请求时出现钩子问题

Formik验证不适用于物料UI自动完成

使用Reaction钩子窗体验证可选字段

StyleX中的多语言支持

我如何在不被 destruct 的情况下将导航栏固定在顶部?

在React中使用映射创建flex组件

如何使用react-router-dom保护嵌套在受保护路由中的嵌套路由?

如何测试根据 prop 更改 CSS 属性的 useEffect 钩子?

REACT: UseState 没有更新变量(ant design 模态形式)

使用reactrouterdom时显示"对象无效作为React子组件"错误

在遵循 react-navigation 的官方文档时收到警告消息

每次状态更改时都会提交react 表单

条件渲染元素的测试不起作用

来自一个自定义 React Native 组件的样式从另一个自定义组件移除样式

Github 页面无法正确呈现 CSS,因为它是本地的

React Router v6 - 访问嵌套路由和处理手写 url 的正确方法

如何在 JSX 中使用 -webkit- 前缀?

如何在react 日历中自定义带有圆形边框的日期项?

无法有条件地更新useEffect中的setState

仅在重新渲染后设置状态