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

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

Code is:

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

I get the following TS error:

[t

相关标签:
10条回答
  • 2020-12-04 15:18

    You need to type result to an array of string const result: string[] = [];.

    0 讨论(0)
  • 2020-12-04 15:20

    All you have to do is define your result as a string array, like the following:

    const result : string[] = [];
    

    Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

    0 讨论(0)
  • 2020-12-04 15:27

    Remove "strictNullChecks": true from "compilerOptions" or set it to false in the tsconfig.json file of your Ng app. These errors will go away like anything and your app would compile successfully.

    Disclaimer: This is just a workaround. This error appears only when the null checks are not handled properly which in any case is not a good way to get things done.

    0 讨论(0)
  • 2020-12-04 15:32

    I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:

    const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...
    
    0 讨论(0)
  • 2020-12-04 15:34

    The solution i found was

    const [files, setFiles] = useState([] as any);
    
    0 讨论(0)
  • 2020-12-04 15:36

    I was able to get past this by using the Array keyword instead of empty brackets:

    const enhancers: Array<any> = [];
    

    Use:

    if (typeof devToolsExtension === 'function') {
      enhancers.push(devToolsExtension())
    }
    
    0 讨论(0)
提交回复
热议问题