Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why typescript doesn't know that i checked for object type?

I want to build such a function:


const recursionProxy = <T extends object>(subject: T) =>
  new Proxy(subject, {
    get(target, key: keyof T) {
      const nestedSubject = target[key];

      if (typeof nestedSubject === "object") {
        return recursionProxy(nestedSubject);
      }

      return nestedSubject ?? target._ ?? "Message not set";
    },
  });

but under the line recursionProxy(nestedSubject); there is an error that says

[i] Argument of type 'T[keyof T]' is not assignable to parameter of type 'object'.

why typescript doesn’t take that if staement in consideration,
in side the if statement nestedSubject is of type object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It does seem to work if you use a type predicate :

const isObject = (f: any): f is object => {
   if(typeof f === "object") return true;
return false;
}
const recursionProxy = <T extends object>(subject: T) =>
  new Proxy(subject, {
    get(target, key: keyof T) {
      const nestedSubject = target[key];

      if (isObject(nestedSubject)) {
        return recursionProxy(nestedSubject);
      }

      return nestedSubject ?? target._ ?? "Message not set";
    },
  });

Link

A null check can also be added in the predicate, if that is required:

const isObject = (f: any): f is object => {
  if(f === null) return false;
   if(typeof f === "object") return true;
return false;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading