【问题标题】:Set type of state of React Component with TypeScript使用 TypeScript 设置 React 组件的状态类型
【发布时间】:2020-08-12 16:49:54
【问题描述】:

我正在尝试在我的 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”类型中的属性“状态”不能分配给相同的 基类型 'Component'。类型'{成分:{[IngridientType.Salad]:数字; [IngridientType.Cheese]:数字; }; }' 不可分配给类型 '只读>'。

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

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:
    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,
        },
      }
    }
    
    

    由于您只使用部分集合初始化您的状态,您将需要使用Partial。 您的IngredientsListType 也可以简化为Record

    旁注,Ingridient 应拼写为Ingredient

    https://codepen.io/drGreen/details/wvKeNyB

    【讨论】:

    • 我敢打赌 Partial 在这里是多余的,因为我认为如果不是状态中提供的枚举中的每个条目,他希望 ts 抛出错误。
    • 也许 - 从他的示例中并不清楚,但现在可以在 React 应用程序中编译
    【解决方案2】:

    我在 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% 确定。不过上面的例子可能更友好

    【讨论】:

    • 和以前一样
    • @goskan93 考虑向我提供您的打字稿版本和问题中提到的整个组件
    猜你喜欢
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2020-02-09
    • 2017-11-28
    • 2020-05-25
    • 2022-08-21
    • 1970-01-01
    相关资源
    最近更新 更多