Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A spread argument must either have a tuple type or be passed to a rest parameter React

I have this code in Typescript:

const [history, setHistory] = useState([Array(9).fill(null)]);
const newHistory = history.slice(0, currentStep + 1);

and when I want to set new State using spread operators like that:

setHistory(...newHistory);

I have errors:

A spread argument must either have a tuple type or be passed to a rest parameter.

Can someone can help my, how I can properly types this?

like image 974
Mateusz Matuś Kowalski Avatar asked Aug 13 '21 08:08

Mateusz Matuś Kowalski


1 Answers

In general, you can avoid such errors by using apply

setHistory(...newHistory); //drops error

setHistory.apply(null, newHistory) //works

but in your example there's a problem: you init history with [[null, null, null...]] then get it, slice to [[null, null, ...], ...] and try to set it back as setHistory([null, null], null).

it seems that you just need to use setHistory(newHistory);

like image 67
Mike Avatar answered Sep 21 '22 16:09

Mike