[英]Type 'string' is not assignable to type 'never' and Type 'unknown' is not assignable to type 'never' error in react typescript
I have a function in React Typescript我在 React Typescript 中有一个 function
const filter = (data: any) => {
if (Array.isArray(data)) {
const temp = data.reduce((r, v) => {
v = filter(v);
if (v !== "") r.push(v);
return r;
}, []);
return temp.length ? temp : "";
}
if (data && typeof data === "object") {
const temp = Object.entries(data).reduce((r, [k, v]) => {
v = filter(v);
if (v !== "") r.push([k, v]);
return r;
}, []);
return temp.length ? Object.fromEntries(temp) : "";
}
return data;
};
but here in line if (v.== "") r,push([k; v]);
但这里符合
if (v.== "") r,push([k; v]);
I am getting error Type 'string' is not assignable to type 'never'.ts(2322)
and Type 'unknown' is not assignable to type 'never'.ts(2322)
in k
and v
respectively, but I am not getting any solution to fix these issues.我收到错误
Type 'string' is not assignable to type 'never'.ts(2322)
和Type 'unknown' is not assignable to type 'never'.ts(2322)
分别分配给k
和v
中的类型'从不'.ts(2322),但我没有得到解决这些问题的任何解决方案。 I am new with Typescript.我是 Typescript 的新手。
Typescript is not able to figure out the correct type of r
in your reduce, so it assumes it to be never[]
. Typescript 无法在您的 reduce 中
r
的正确类型,因此假定它是never[]
。 You can get around this by specifiyng the correct type yourself.您可以通过自己指定正确的类型来解决此问题。
const filter = (data: any) => {
if (Array.isArray(data)) {
const temp = data.reduce((r, v) => {
v = filter(v);
if (v !== "") r.push(v);
return r;
}, []);
return temp.length ? temp : "";
}
if (data && typeof data === "object") {
const temp = Object.entries(data).reduce((r, [k, v]) => {
v = filter(v);
if (v !== "") r.push([k, v]);
return r;
}, [] as [string, unknown][]);
return temp.length ? Object.fromEntries(temp) : "";
}
return data;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.