reactjs - 使用 TypeScript 设置 React 组件的状态类型

标签 reactjs typescript

我正在尝试在我的 React 项目中使用 TypeScript


export enum IngridientType {
  BreadBottom = "BreadBottom",
  BreadTop = "BreadTop",
  Meat = "Meat",
  Cheese = "Cheese",
  Bacon = "Bacon",
  Salad = "Salad",
  Seeds1 = "Seeds1",
  Seeds2 = "Seeds2",
}

export type IngredientsListType<R> = { [key in keyof typeof IngridientType]?: R };

type IBurgerBuilderState<T> = { ingredients: IngredientsListType<T> };

class BurgerBuilder extends Component<{}, IBurgerBuilderState<number>> {
  state = {
    ingredients: {
       [IngridientType.Bacon]: 2,
       [IngridientType.Cheese]: 2,
    },
  };

...
}

但我收到错误

Property 'state' in type 'BurgerBuilder' is not assignable to the same property in base type 'Component<{}, IBurgerBuilderState, any>'. Type '{ ingredients: { [IngridientType.Salad]: number; [IngridientType.Cheese]: number; }; }' is not assignable to type 'Readonly>'.

我不明白这里到底出了什么问题..

最佳答案

我在 TypeScript Playground 中使用您的代码进行调整,并提出了以下方法 - 将您的枚举与简单的通用类型一起使用:

export enum IngridientType {
  BreadBottom = "BreadBottom",
  BreadTop = "BreadTop",
}

type IngridientsType<T extends string, U> = {
    [K in T]: U;
};

interface IState {
  ingredients: IngridientsType<IngridientType, number>;
}

const state: IState = {
  ingredients: {
    [IngridientType.BreadTop]: 0,
    [IngridientType.BreadBottom]: 2,
    someOtherIngredient: 'wrongType', // ts will throw errors on it
  }
}

编辑:如果您问我示例中出现错误的原因是什么,我不能 100% 确定。然而上面的例子可能更友好一点?

关于reactjs - 使用 TypeScript 设置 React 组件的状态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61487566/

相关文章:

javascript - 如何限制详细信息列表中的最大项目行数?

reactjs - React 从嵌套元素中的另一个组件更新组件

angular - 修改 TestBed.overrideComponent 中定义的组件

angular - TypeScript 编译失败,因为 'any' 的类型声明失去类型安全

Angular 4 模板错误 : 'anonymous' does not contain such a member

javascript - 如何将组件注入(inject)到Angular2中的div选择器中

angular - 如何使用 TypeScript 4.1.2 在 Angular 6 中绑定(bind) img src

reactjs - '(dispatch: Dispatch) => void' 类型的参数不可分配给 'AnyAction' 类型的参数

reactjs - useState加载在异步之前不更新

javascript - ReactJS:未捕获的语法错误:意外的 token (