代码是:

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

我得到以下TS错误:

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

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


当前回答

当您在没有设置对象属性的情况下设置对象中的属性值时,会发生此错误。声明带有属性的对象类型,然后在实例化对象时分配该类型。现在您可以设置属性值而不会出现此错误。

其他回答

你所要做的就是将结果定义为一个字符串数组,如下所示:

const result : string[] = [];

如果没有定义数组类型,默认情况下将为never。因此,当您尝试向它添加字符串时,它是类型不匹配,因此抛出您所看到的错误。

你需要输入result到字符串const result的数组:string[] =[];。

我能够通过使用Array关键字而不是空括号来解决这个问题:

const enhancers: Array<any> = [];

使用:

if (typeof devToolsExtension === 'function') {
  enhancers.push(devToolsExtension())
}

你也可以添加字符串[]

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);