代码是:
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吗?
当前回答
在使用ReactJS Hook时,我在ReactJS无状态函数中出现了同样的错误 useState。 我想设置一个对象数组的状态,如果我用下面的方法
const [items , setItems] = useState([]);
并像这样更新状态:
const item = { id : new Date().getTime() , text : 'New Text' };
setItems([ item , ...items ]);
我得到了错误: 类型为'{id: number;any}'不能赋值给类型为'never'的形参
但如果这样做,
const [items , setItems] = useState([{}]);
错误消失了,但有一个项目在0索引没有任何数据(不想要)。
所以我找到的解决方案是:
const [items , setItems] = useState([] as any);
其他回答
我在React函数组件中得到了相同的错误,使用useState钩子。
解决方案是在初始化时使用尖括号声明useState的类型:
// Example: type of useState is an array of string
const [items , setItems] = useState<string[]>([]);
你需要输入result到字符串const result的数组:string[] =[];。
从"compilerOptions"中删除"strictNullChecks": true或在tsconfig中将其设置为false。这些错误会像任何东西一样消失,你的应用程序将成功编译。
免责声明:这只是一个变通方案。此错误仅在null检查未正确处理时出现,这在任何情况下都不是完成工作的好方法。
你也可以添加字符串[]
const foo = (foo: string) => {
const result = []
(result as string[]).push(foo)
}
当它是物体的一部分时,我就这么做了
let complexObj = {
arrData : [],
anotherKey: anotherValue
...
}
(arrData as string[]).push('text')
这个错误还有一个原因。 如果你在使用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} />
}