akibo
akibo

Reputation: 715

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

Upvotes: 4

Views: 9044

Answers (3)

Ravi Sevta
Ravi Sevta

Reputation: 3085

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

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

Upvotes: 8

hendrixchord
hendrixchord

Reputation: 5434

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

The compiler needs to know the type of the array.

Upvotes: 0

Anh Tuan
Anh Tuan

Reputation: 1143

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

just try to define your init array

Upvotes: 0

Related Questions