gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:22:07 25 4
gpt4 key购买 nike

我正在尝试在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com