为什么打字稿不知道我检查了对象类型?

mod*_*7ex 3 javascript typescript reactjs

我想建立这样一个功能:


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";
    },
  });

Run Code Online (Sandbox Code Playgroud)

但在该行下面recursionProxy(nestedSubject);有一个错误说

[i] Argument of type 'T[keyof T]' is not assignable to parameter of type 'object'.
Run Code Online (Sandbox Code Playgroud)

为什么打字稿不考虑 if 语句,在 if 语句内部nestedSubject是对象类型

Tus*_*ahi 5

如果您使用类型谓词,它似乎确实有效:

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";
    },
  });

Run Code Online (Sandbox Code Playgroud)

关联

如果需要,还可以在谓词中添加空检查:

const isObject = (f: any): f is object => {
  if(f === null) return false;
   if(typeof f === "object") return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)