0

I want to push new item into my initial state array, using useState hook ,but im getting error: TS2322 Type number is not assignable to type 'never'. ([...pageNumbers, i) underlined

My code:

const [pageNumbers, setPageNumbers] = useState([]);

  for (
    let i = 1;
    i <= Math.ceil(props.totalCommits / props.CommitsPerPage);
    i++
  ) {
    setPageNumbers([...pageNumbers, i]);
  }

2 Answers 2

1

You need to type the state array like this:

const [pageNumbers, setPageNumbers] = useState<Array<number>>([]);
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't add a <type> when initializing a empty array, typescript will assume the type as React.SetStateAction<never[]>. So, when you tried to add let i = 1, type number into type never, typescript threw the error Type number is not assignable to type 'never'.

You can assign a type when initializing to fix this issue as following.

 const [pageNumber, setPageNumbers] = useState<number[]>([]);

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.