代码是:
const foo = (foo: string) => {
const result = []
result.push(foo)
}
我得到以下TS错误:
string类型的实参不能赋值给never类型的形参。
我做错了什么?这是一个bug吗?
代码是:
const foo = (foo: string) => {
const result = []
result.push(foo)
}
我得到以下TS错误:
string类型的实参不能赋值给never类型的形参。
我做错了什么?这是一个bug吗?
当前回答
我能够通过使用Array关键字而不是空括号来解决这个问题:
const enhancers: Array<any> = [];
使用:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
其他回答
我找到的解决办法是
const [files, setFiles] = useState([] as any);
错误:“any”类型的实参不能赋值给“never”类型的形参。
在tsconfig。json -
"noImplicitReturns": false,
"strictNullChecks":false,
解决方案:输入'never'
我在React函数组件中得到了相同的错误,使用useState钩子。
解决方案是在初始化时使用尖括号声明useState的类型:
// Example: type of useState is an array of string
const [items , setItems] = useState<string[]>([]);
我能够通过使用Array关键字而不是空括号来解决这个问题:
const enhancers: Array<any> = [];
使用:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
这似乎是typescript中一些奇怪的行为,因为遗留的原因而被困住了。如果你有代码:
const result = []
通常你会这样写:
const result:any[] = []
然而,如果你在你的tsconfig中同时设置了noImplicitAny FALSE和strictNullChecks TRUE,它将被视为:
const result:never[] = []
恕我直言,这种行为完全不合逻辑。打开空检查改变数组的条目类型??然后打开noImplicitAny实际上恢复使用any没有任何警告??
当你真的有一个any的数组时,你不需要用额外的代码来指明它。