2

I have a state in React something like this:

type MyState = {
  xCount: number;
  yCount: number;
};

I want to access a state without knowing it's name while coding the program.

export class BodyWidget extends React.Component<BodyWidgetProps> {
  state: MyState = {
    xCount: 1,
    yCount: 1
  };

returnState = (name:any) {
  return this.state[name]
}

...
}

When I am trying this i get this error:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'MyState'.

oldBear
  • 157
  • 2
  • 10

2 Answers2

4

try

returnState = (name: keyof MyState) {
  return this.state[name]
}
D Pro
  • 1,756
  • 1
  • 8
  • 15
-1

The error says that 'name' should be one of MyState properties(xCount or yCount), like this:

returnState = (name: keyof MyState) => {
    return this.state[name];
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Milos Kovacevic
  • 861
  • 1
  • 9
  • 20