You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular TS中实现Object.prototype.get()方法报错求助

我来帮你搞定这两个报错,咱们一步步拆解问题:

先解决运行时的属性描述符错误

你遇到的Invalid property descriptor错误,主要有两个原因:

  1. 环境限制:在Chrome这类浏览器中,用Object.defineProperties给Object.prototype添加名为get的数据属性会触发内置限制(推测是因为get作为访问器关键字的特殊处理),直接给原型赋值方法就能绕过这个问题。
  2. 箭头函数的this绑定错误:你用了箭头函数作为方法,箭头函数的this是定义时的上下文(不是调用该方法的对象),改成普通函数才能正确拿到调用者的this。

再解决TypeScript的类型报错

TS报错Property 'get' does not exist on type 'Object',是因为TS的类型系统不知道我们给Object.prototype扩展了新方法。需要通过声明合并扩展Object接口,让TS识别这个新增的get方法。

完整的可运行代码

// 扩展Object接口,让TypeScript认识我们新增的get方法
declare global {
  interface Object {
    get(key: string, defaultValue?: any): any;
  }
}

// 给Object.prototype添加get方法,用普通函数保证this正确绑定
Object.prototype.get = function(key: string, defaultValue = null) {
  // 这里的this就是调用方法的对象(比如a.get('a')里的a)
  if (!this || !key) {
    return defaultValue;
  }

  const keyArr = key.split('.');
  let current = this;
  let result: any;

  while (keyArr.length > 0) {
    const itemKey = keyArr.shift();
    if (current == null) {
      return defaultValue;
    }

    // 处理数组场景:如果当前是数组,且itemKey不是数字索引
    if (Array.isArray(current) && isNaN(Number(itemKey))) {
      const resultArr = current.map((_, index) => {
        // 拼接新路径,递归调用get方法
        return current[index].get([itemKey, ...keyArr].join('.'), defaultValue);
      }).filter(res => res !== null);

      return resultArr.length ? resultArr : defaultValue;
    }

    result = current[itemKey as keyof typeof current];
    current = result;
  }

  return result !== undefined ? result : defaultValue;
};

// 测试用例
const a = {a: 1};
console.log(a.get('a')); // 输出1

const nestedObj = {user: {profile: {age: 25}}};
console.log(nestedObj.get('user.profile.age')); // 输出25

const arr = [{name: 'Bob'}, {name: 'Charlie'}];
console.log(arr.get('name')); // 输出["Bob", "Charlie"]

额外优化说明

我还调整了原代码的逻辑:

  • 用循环替代递归,避免深层嵌套路径导致的栈溢出问题。
  • 修正了数组处理时的路径拼接逻辑,原代码里的keyArr.unshift(k, itemKey)会修改原数组,导致后续递归出错,现在改成了拼接新数组,不影响原数据。

内容的提问来源于stack exchange,提问作者Никита Середа

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:45:29