React、Typescript 和 setState({ [name]: value }) 错误

React, Typescript, and a setState({ [name]: value }) error

我在过去几个月一直在开发几个 create-react-app + TypeScript 应用程序。在某些时候(我可能升级了 lib)tslint 在给状态一个类型时开始在 this.setState({ [name]: value }) 上抛出错误。它曾经让它滑动(除非我疯了......不是不可能的)。

让 tslint 闭嘴的唯一方法是将状态类型更改为 any,我不想这样做。如果我保存文件并让 yarn start 接受更改,它运行良好......所以我能够忽略 tslint 在 vscode.

中抛出的错误

我明白为什么 tslint 会抛出错误。我想知道是否可以设置一条规则来忽略这个特定错误?

我在哪里看到的示例(第 5 行):

class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
...
private handleOnChange = (event: any) => {
    const { name, value } = event.target;
    this.setState({ [name]: value });        <-- tslint no likey
}

错误:

[ts] Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IMyComponentState| ((prevState: Readonly, pro...'. Type '{ [x: number]: any; }' is not assignable to type 'Pick

class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
...
private handleOnChange = (event: any) => {
    const { name, value } = event.target;

    // @ts-ignore
    this.setState({ [name]: value });        <-- tslint no likey
}

你也会在这里使用这个解决方案:

interface IState {
    [key: string]: any; // or the type of your input
} 

我想这比忽略警告要好。

您可以将 属性 [key: string]: any; 添加到现有接口声明 IMyComponentState

interface IMyComponentState{
  ...existing fields,
  [x:string]:any
}