在 Typescript 中访问具有动态键名的状态

Accessing a state with dynamic key name in Typescript

我在 React 中有这样的状态:

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

我想在编写程序时访问一个不知道其名称的状态。

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

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

...
}

当我尝试此操作时出现此错误:

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

尝试

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

错误表明 'name' 应该是 MyState 属性之一(xCount 或 yCount),如下所示:

returnState = (name: keyof MyState) => {
    return this.state[name];
}