5

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

0

3 Answers 3

6
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
}
Sign up to request clarification or add additional context in comments.

5 Comments

vscode doesn't seem to be responding to that comment. Could it be because this is an error and not a warning/suggestion?
did you remove the <optional rule identifier> ?
Yes :) Maybe this is an issue with vscode's tslint extension.
hmm, just tried in vscode and it looks like // @ts-ignore works
Not sure where I found it, but it appears to come straight from the ts docs after ts 2.6: typescriptlang.org/docs/handbook/release-notes/…
5

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.

1 Comment

Marking this as the proper solution, rather than peppering // @ts-ignore comments all over the place. Thank you!
0

You can add property [key: string]: any; to existing interface declaration IMyComponentState i.e

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.