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

Time:08-22

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

CodePudding user response:

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;
}
  • Related