Home > Net >  Getting typescript error when pushing object into state array with useState
Getting typescript error when pushing object into state array with useState

Time:10-15

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]);
  }

CodePudding user response:

You need to type the state array like this:

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

CodePudding user response:

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[]>([]);

  • Related