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

如何在TypeScript定义文件(.d.ts)中声明猴子补丁后的类?

解决TypeScript猴子补丁后的类型定义问题

问题背景

现有类A的定义:

class A {
    constructor();
    someFunction(): void;
}

类B的属性直接使用A的实例:

class B {
    aProperty: A;
}

需要为类C编写.d.ts文件,其中aProperty是被猴子补丁添加了someOtherFunction(): void的A实例,实际等效于A类新增了该方法。之前尝试用联合类型A | { someOtherFunction(): void; }定义,但无法正常工作。

正确定义方式

方式1:使用交叉类型

交叉类型可以将A的类型与包含新方法的对象类型合并,表示aProperty同时具备两者的所有成员:

class C {
    aProperty: A & { someOtherFunction(): void; };
}

方式2:扩展接口定义

先声明一个继承自A的接口,添加新方法,再用这个接口作为属性类型:

interface AWithExtraMethod extends A {
    someOtherFunction(): void;
}

class C {
    aProperty: AWithExtraMethod;
}

方式3:全局声明合并(仅当猴子补丁全局生效时使用)

如果这个猴子补丁是对A类全局生效的,所有A实例都具备someOtherFunction,可以通过声明合并扩展A的类型:

declare class A {
    someOtherFunction(): void;
}

class C {
    aProperty: A;
}

为什么之前的联合类型不行

A | { someOtherFunction(): void; }是联合类型,表示aProperty要么是纯A实例(没有someOtherFunction),要么是仅包含someOtherFunction的对象,而非同时拥有两者的实例。因此访问aProperty.someOtherFunction()时,TypeScript会因类型不确定而报错。而交叉类型A & X则表示同时拥有A和X的所有成员,完全匹配猴子补丁后的实例特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:02:41