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[];
};
}
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[];
};
}
Or perhaps with an additional type to make things cleaner.
interface SomeLists {
itmesA: string[];
itmesB: string[];
}
export interface StateInterface {
list: SomeLists & {
current: keyof SomeLists;
};
}
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.