问题
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