[英]React + Typescript: Type of React component with no state/no props
[英]Set type of state of React Component with 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,
},
};
...
}
但我收到一個錯誤
'BurgerBuilder' 類型中的屬性 'state' 不能分配給基本類型 'Component<{}、IBurgerBuilderState、any>' 中的相同屬性。 類型'{成分:{[IngridientType.Salad]:數字; [IngridientType.Cheese]:數字; }; }' 不可分配給類型 'Readonly>'。
我不明白這里到底是什么問題..
我正在使用您的代碼在 TypeScript 操場上進行調整,並提出了以下方法 - 將您的enum
與一個簡單的generic type
一起使用:
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% 確定。 但是上面的例子可能更友好一點?
export enum IngridientType {
BreadBottom = 'BreadBottom',
BreadTop = 'BreadTop',
Meat = 'Meat',
Cheese = 'Cheese',
Bacon = 'Bacon',
Salad = 'Salad',
Seeds1 = 'Seeds1',
Seeds2 = 'Seeds2',
}
export type IngredientsListType<R> = Record<IngridientType, R>
type IBurgerBuilderState<T> = { ingredients: Partial<IngredientsListType<T>> }
export class BurgerBuilder extends Component<{}, IBurgerBuilderState<number>> {
state = {
ingredients: {
[IngridientType.Bacon]: 2,
[IngridientType.Cheese]: 2,
},
}
}
由於您僅使用部分集初始化 state ,因此您將需要使用Partial
。 您的IngredientsListType
也可以使用Record
進行簡化。
旁注, Ingridient
應拼寫為Ingredient
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.