代码是:

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

我得到以下TS错误:

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

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


当前回答

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

其他回答

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

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

您需要指定数组是什么,因为result =[]的返回类型为任意[]。通常情况下,你想要避免任何类型,因为根据微软的说法,它们意味着被用作“逃生舱口”。

结果是一个字符串数组的对象。

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

你也可以添加字符串[]

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

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

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

这似乎是typescript中一些奇怪的行为,因为遗留的原因而被困住了。如果你有代码:

const result = []

通常你会这样写:

const result:any[] = []

然而,如果你在你的tsconfig中同时设置了noImplicitAny FALSE和strictNullChecks TRUE,它将被视为:

const result:never[] = []

恕我直言,这种行为完全不合逻辑。打开空检查改变数组的条目类型??然后打开noImplicitAny实际上恢复使用any没有任何警告??

当你真的有一个any的数组时,你不需要用额外的代码来指明它。