Home > Mobile >  How to add key signature to a string so it can work as an index for an object?
How to add key signature to a string so it can work as an index for an object?

Time:12-02

How to add a signature to this interface so typescript will understand that the current value might serve as an index for a certain object I am getting the error of Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

export interface StateInterface {
  list: {
    current: string;  // itmesA or itmesB
    itmesA: string[];
    itmesB: string[];
  };
  
const state =   
   list: {
    current: 'itemesA'
    itmesA: ['1','2','3'];
    itmesB: ['4','5','6'];
  };
  
 let showItems = context.list[context.list.current][0]}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

string could be anything, but only specific strings can be used to index that object. So that means you could make the keys more specific so that the current property can only be one of the right keys.


export interface StateInterface {
  list: {
    current: 'itmesA' | 'itmesB';
    itmesA: string[];
    itmesB: string[];
  };
}

Playground


Or more cleverly so you don't have to type the key names twice:

export interface StateInterface {
  list: {
    current: keyof StateInterface['list']; // though this makes `current` a valid key
    itmesA: string[];
    itmesB: string[];
  };
}

Playground


Or perhaps with an additional type to make things cleaner.

interface SomeLists {
  itmesA: string[];
  itmesB: string[];
}

export interface StateInterface {
  list: SomeLists & {
    current: keyof SomeLists;
  };
}

Playground


There's a lot of way to go about this. Which to choose is somewhat opinion based guided by how this type will be used.

  • Related