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

做~自己de王妃 提交于 2020-02-02 13:16:39

问题


I have a couple create-react-app + TypeScript apps that I've been working on over the past few months. At some point (I probably upgraded the lib) tslint started throwing errors on this.setState({ [name]: value }) when state is given a type. It used to let it slide (unless I'm going crazy... not out of the question).

The only way to get tslint to shut up about it, is to change the state type to any, which I don't want to do. If I save the file and let yarn start pick up the change, it runs fine... so I'm able to ignore the error that tslint throws in vscode.

I understand WHY tslint is throwing an error. I'm wondering if there's a rule I can set to ignore this particular error?

Example of where I see this (line 5):

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

The error:

[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


回答1:


You'd use this solution here too:

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

I guess thats better than just ignoring the warnings.




回答2:


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
}


来源:https://stackoverflow.com/questions/51409931/react-typescript-and-a-setstate-name-value-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!