What is “not assignable to parameter of type never” error in typescript?

前端 未结 10 2210
無奈伤痛
無奈伤痛 2020-12-04 15:08

Code is:

const foo = (foo: string) => {
  const result = []
  result.push(foo)
}

I get the following TS error:

[t

10条回答
  •  旧时难觅i
    2020-12-04 15:43

    I was having same error In ReactJS statless function while using ReactJs Hook useState. I wanted to set state of an object array , so if I use the following way

    const [items , setItems] = useState([]);
    

    and update the state like this:

     const item = { id : new Date().getTime() , text : 'New Text' };
     setItems([ item , ...items ]);
    

    I was getting error:

    Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'

    but if do it like this,

    const [items , setItems] = useState([{}]);
    

    Error is gone but there is an item at 0 index which don't have any data(don't want that).

    so the solution I found is:

    const [items , setItems] = useState([] as any);
    

提交回复
热议问题