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

让TypeScript识别通过Object.prototype添加的新方法

解决TypeScript识别Object.prototype扩展方法的问题

要让TypeScript识别你给Object.prototype添加的l方法,核心是全局扩展Object接口,同时要注意代码语法和TS的模块/脚本环境差异,以下是具体方案:

1. 先修正原型扩展的代码

你的原代码语法有误,箭头函数无法绑定正确的this(会指向全局而非调用对象),需要改成普通函数:

Object.prototype.l = function (title: string) {
    console.log({ [title]: this });
    return this;
};

2. 全局扩展Object接口(分两种场景)

场景1:非模块脚本(无import/export)

直接在代码中扩展Object接口,TS会自动合并全局接口声明:

// 先声明接口扩展
interface Object {
    l(title: string): this;
}

// 再实现原型方法
Object.prototype.l = function (title: string) {
    console.log({ [title]: this });
    return this;
};

// 现在调用不会报错
const bar = foo().l('bar');

场景2:模块文件(有import/export)

如果你的代码是模块(包含import/export),需要用declare global包裹接口声明,确保扩展的是全局Object类型:

declare global {
    interface Object {
        l(title: string): this;
    }
}

Object.prototype.l = function (title: string) {
    console.log({ [title]: this });
    return this;
};

// 模块文件必须有导出(即使是空对象),否则TS不会识别为模块
export {};

场景3:使用.d.ts声明文件

如果你想把类型声明单独放在.d.ts文件中,创建一个global.d.ts文件,内容如下:

// global.d.ts
interface Object {
    l(title: string): this;
}

然后确保你的tsconfig.json的include数组包含这个文件的路径,比如:

{
    "include": ["./src/**/*", "./global.d.ts"]
}

3. JsDoc替代方案(无需全局扩展)

如果不想全局修改Object类型,也可以用JsDoc临时标注类型:

/** @type {{ l(title: string): ReturnType<typeof foo> }} */
const fooResult = foo();
const bar = fooResult.l('bar');

关键说明

  • 用this作为返回类型,能保证链式调用时保留原对象的类型,而不是降级为Object类型。
  • 确保你的TS配置没有禁用全局类型扩展(默认是允许的)。

内容的提问来源于stack exchange,提问作者cayge sinnett

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:13:14