0

Im pretty new to Typescript, and have hit an error I dont quite know how to fix.

Im getting the error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ 'lf-text': typeof AddonLfTextModel; 'lf-image': typeof AddonLfImageModel; gameflow: typeof AddonGameflowModel; }'.
No index signature with a parameter of type 'string' was found on type '{ 'lf-text': typeof AddonLfTextModel; 'lf-image': typeof AddonLfImageModel; gameflow: typeof AddonGameflowModel; }'.

Im not quite sure on how to solve this TS compile error??

In my class I have these types and interfaces:

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[];
}

In my code (In a method), im trying to to the following, but getting the error: (The _state is outside the method, but in a class)

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
      };
    });
  }
envy
  • 327
  • 1
  • 5
  • 14
  • 1
    Did reading through [any of the other 332 questions about the same error](https://stackoverflow.com/search?q=is%3Aq+Element+implicitly+has+an+%27any%27+type+because+expression+of+type+%27string%27+can%27t+be+used+to+index+type) answer your question? – Heretic Monkey Mar 15 '21 at 19:48
  • Yeah, i found that I could just do the type on :any to the "mapping", but that doesn't quite feel like the "correct" solution... – envy Mar 15 '21 at 19:57
  • Does this answer your question? [Why doesn't Object.keys return a keyof type in TypeScript?](https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript) – Heretic Monkey Mar 15 '21 at 20:22

1 Answers1

2

Change definition of ContentAddon to-

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

Reason

The type of addon.alias is string but the object AddonMapping allows only 3 particular keys. So any arbitrary string can not be used to index the object AddonMapping

Shivam Singla
  • 2,117
  • 1
  • 10
  • 22