为什么typescript不知道我检查了对象的类型

28 阅读1分钟

我想建立这样一个函数:


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

但在recursionProxy(nestedSubject); ,有一个错误,说

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

为什么 typescript 不考虑 if 语句,在 if 语句的旁边nestedSubject 是对象类型。