代码是:

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

其他回答

我找到的解决办法是

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

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

const enhancers: Array<any> = [];

使用:

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

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

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

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

在最新版本的angular中,你必须定义变量的类型:

如果它是一个字符串,你必须这样做: 公开信息:string =""; 如果是数字: 公共n: number=0; 如果一个string的表: 公共标签:字符串[]= []; 如果用数字表表示: 公共标签:number[]=[]; 如果是混合表: 公共标签:any[] = []; ……Etc(用于其他类型的变量) 如果你没有定义变量的类型:默认情况下,类型为never

注意:在你的情况下,你必须知道你的表必须包含的变量类型,并选择正确的选项(如选项3,4,5)。

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

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