简体   繁体   中英

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

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]); 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. I am new with Typescript.

Typescript is not able to figure out the correct type of r in your reduce, so it assumes it to be 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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM