Blablabla
Blablabla

Reputation: 305

React TS spread operator

My goal is to spread new item (query) to dataList. It is functional component.

const [dataList, setDataList] = useState([]);

  const transferData = (query: string) => {
    setDataList([...dataList, query]);
  };

Code is written in React Typescript and my editor is shouting:

Argument of type 'string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type 'string[]' is not assignable to type 'never[]'.
    Type 'string' is not assignable to type 'never'.

Typescript is brand new feature for me, so dont know how to fix it and what does it mean. Thanks.

Upvotes: 0

Views: 284

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371148

You have:

const [dataList, setDataList] = useState([]);

That's an empty array, and you haven't used any type parameters, so dataList is typed to be Array<never> (and setDataList can only accept the same sort of parameter: Array<never>).

Since you're going to be populating the array with strings, you need to tell TS that when you call useState:

const [dataList, setDataList] = useState<Array<string>>([]);

Upvotes: 1

Related Questions