简体   繁体   English

为什么 typescript 不知道我检查了 object 类型?

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

I want to build such a function:我想构建这样一个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);但在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为什么 typescript 没有考虑到 if 语句,在 if 语句中nestedSubject的类型是 object

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:如果需要,还可以在谓词中添加 null 检查:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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