Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string[]' is not assignable to type 'never[]'

In typescript, I got error of Type 'string[]' is not assignable to type 'never[]'.

I want to add 'abc' into the array, what's wrong with it?

export default function App() {
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState([]);

  const xx = () => setArr([...arr, text]);

  return <div className="App">{text}</div>;
}

https://codesandbox.io/s/boring-spence-08g8r?file=/src/App.tsx:56-272

like image 271
akibo Avatar asked Sep 19 '25 17:09

akibo


1 Answers

useState is a generic function so use it to define the type of array.

like: const [arr, setArr] = React.useState<string[]>([]);

like image 198
Ravi Sevta Avatar answered Sep 22 '25 11:09

Ravi Sevta