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