简体   繁体   中英

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.

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>>([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM