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

Viewed 2525

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

3 Answers

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

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

  const initArr: string[] = [];
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState(initArr);

just try to define your init array

const [arr, setArr] = React.useState([] as string[]);

The compiler needs to know the type of the array.

Related