0

I have an array in state

state = {
        array: [],
    };

Later I do this

method = (el): void => {
        const {array} = this.state;
        const includesEl = array.includes(el);
}

And I'm getting an error

 Argument of type 'any' is not assignable to parameter of type 'never'.

I type state interface like this

export interface State{
    array: any[],
}

Should I type the state in state declaration as well? Because I assume the error is coming from the face that I'm setting array initially to []

1
  • Any online code sample of your question? Since info may be lacked. Commented Feb 28, 2020 at 8:44

3 Answers 3

1

Did you try:

state: State = {
    array: []
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Strange because I already have it like this class Component extends React.Component<Props, State>
Here is what I found: This is because they work in two different ways, the 2nd generic type parameter will allow this.setState() to work correctly, because that method comes from the base class, but initializing state inside the component overrides the base implementation so you have to make sure that you tell the compiler that you're not actually doing anything different.
0

You have to write a specific type of Argument.

method = (el: `TYPE`): void => {
  ...
}

Comments

0

Add this,

method = (el: []): void => {
        const {array} = this.state;
        const includesEl = array.includes(el);
}

or may be add this to state like state = { array : any as []}

2 Comments

state = { array : any[]} gives 'any' only refers to a type, but is being used as a value here
@Allan or use it with as any[] like Jai suggested

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.