代码是:
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吗?
当前回答
我在React函数组件中得到了相同的错误,使用useState钩子。
解决方案是在初始化时使用尖括号声明useState的类型:
// Example: type of useState is an array of string
const [items , setItems] = useState<string[]>([]);
其他回答
你所要做的就是将结果定义为一个字符串数组,如下所示:
const result : string[] = [];
如果没有定义数组类型,默认情况下将为never。因此,当您尝试向它添加字符串时,它是类型不匹配,因此抛出您所看到的错误。
你需要输入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')
错误:“any”类型的实参不能赋值给“never”类型的形参。
在tsconfig。json -
"noImplicitReturns": false,
"strictNullChecks":false,
解决方案:输入'never'
这个错误还有一个原因。 如果你在使用connect()()包装组件后导出,那么props可能会给出typescript errorSolution:我没有探索太多,因为我可以选择用useSelector钩子替换连接函数 例如
/* Comp.tsx */
interface IComp {
a: number
}
const Comp = ({a}:IComp) => <div>{a}</div>
/* **
below line is culprit, you are exporting default the return
value of Connect and there is no types added to that return
value of that connect()(Comp)
** */
export default connect()(Comp)
--
/* App.tsx */
const App = () => {
/** below line gives same error
[ts] Argument of type 'number' is not assignable to
parameter of type 'never' */
return <Comp a={3} />
}