代码是:

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

我得到以下TS错误:

string类型的实参不能赋值给never类型的形参。

我做错了什么?这是一个bug吗?


当前回答

你也可以添加字符串[]

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

当它是物体的一部分时,我就这么做了

let complexObj = {
arrData : [],
anotherKey: anotherValue
...
}
(arrData as string[]).push('text')

其他回答

我在React函数组件中得到了相同的错误,使用useState钩子。

解决方案是在初始化时使用尖括号声明useState的类型:

// Example: type of useState is an array of string
const [items , setItems] = useState<string[]>([]); 

从"compilerOptions"中删除"strictNullChecks": true或在tsconfig中将其设置为false。这些错误会像任何东西一样消失,你的应用程序将成功编译。

免责声明:这只是一个变通方案。此错误仅在null检查未正确处理时出现,这在任何情况下都不是完成工作的好方法。

错误:“any”类型的实参不能赋值给“never”类型的形参。

在tsconfig。json -

  "noImplicitReturns": false,

   "strictNullChecks":false,

解决方案:输入'never'

你也可以添加字符串[]

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

当它是物体的一部分时,我就这么做了

let complexObj = {
arrData : [],
anotherKey: anotherValue
...
}
(arrData as string[]).push('text')

我找到的解决办法是

const [files, setFiles] = useState([] as any);