【问题标题】:How to solve: 'string' can't be used to index type如何解决:'string'不能用于索引类型
【发布时间】:2021-03-15 19:46:04
【问题描述】:

我对 Typescript 很陌生,遇到了一个我不知道如何解决的错误。

我收到错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{'lf-text':typeof AddonLfTextModel; 'lf-image': AddonLfImageModel 的类型;游戏流:插件游戏流模型的类型; }'。
在类型“{'lf-text': typeof AddonLfTextModel; 'lf-image': AddonLfImageModel 的类型;游戏流:插件游戏流模型的类型; }'。

我不太确定如何解决这个 TS 编译错误??

在我的课堂上,我有这些类型和接口:

export interface ContentAddon {
  id: string;
  alias: string;
  model: ContentAddonType;
}

export type ContentAddonType =
  | AddonLfTextModel
  | AddonLfImageModel
  | AddonGameflowModel;

const AddonMapping = {
  'lf-text': AddonLfTextModel,
  'lf-image': AddonLfImageModel,
  gameflow: AddonGameflowModel
};

interface ColumnModelState {
  size: number;
  addons: ContentAddon[];
}

在我的代码中(在一个方法中),我尝试执行以下操作,但收到错误:(_state 在方法之外,但在一个类中)

private _state?: ColumnModelState;

parse(data: ContentColumnData): void {
    console.log('Column data', data);
    // TODO: Parse data
    const state = this.state;

    state.size = data.size;
    state.addons = data.addons.map((addon: ContentAddon) => {

      //IM GETTING AN ERROR HERE: 'string' can't be used to index type
      if (typeof AddonMapping[addon.alias] === 'undefined') {
        throw new Error(`Unrecognized addon "${addon.alias}"`);
      }

      return {
        id: generateUniqueId(),
        alias: addon.alias,
        model: new AddonMapping[addon.alias](addon) //GETTING A TS ERROR HERE: 'string' can't be used to index type
      };
    });
  }

【问题讨论】:

标签: typescript


【解决方案1】:

ContentAddon的定义更改为-

export interface ContentAddon {
  id: string;
  alias: keyof typeof AddonMapping;
  model: ContentAddonType;
}

原因

addon.alias 的类型是 string,但对象 AddonMapping 只允许 3 个特定键。所以不能使用任意字符串来索引对象AddonMapping

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2022-11-11
    • 1970-01-01
    • 2022-11-15
    • 2021-10-18
    相关资源
    最近更新 更多