在打字稿中向现有类添加方法?

新手上路,请多包涵

我在一个 angular 2 cli 项目中工作,我必须在其中创建一个插件的定义,因为它不存在它的类型。这个插件依赖于一个已经有自己的类型并且可以工作的主库。

无论如何,我有两个文件,其中一个是主文件

图书馆类型文件 A

 export class A extends B {
    constructor(...);
    methodX(): void;
}

而且我需要为我的插件添加一个新方法,这样我的课程就像

export class A extends B {
        constructor(...);
        methodX(): void;
        methodY(): void;
    }

关键是我需要将它添加到一个单独的文件中。问题是在不创建新类的情况下向现有类添加方法

如果我把

插件类型文件 B

 export class A extends B {
    constructor(...);
    methodX(): void;
}

或者

插件类型文件 B

 export class A extends B {
        constructor(...);
        methodX(): void;
        methodY(): void;
}

它不起作用,有没有人如何实现覆盖类或用新方法扩展它?

谢谢

原文由 ackuser 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 243
2 个回答

您可以通过使用新方法创建接口并修改原型来实现。

是这样的:

 class B { }

class A extends B {
    constructor() {
        super();
    }
    methodX(): void { };
    methodY(): void { };
}

interface B {
    newMethod(): void;
}

B.prototype.newMethod = function () { console.log('a') };

这可以让你在做的时候有正确的打字。

 new A().newMethod();

我在 这里%20%7D%3B%0D%0A%0D%0Anew%20A().newMethod()%3B%0D%0A%0D%0A%0D%0A%0D%0A) 做了一个游乐场的例子。

原文由 toskv 发布,翻译遵循 CC BY-SA 3.0 许可协议

TypeScript 文档中的“声明合并 > 模块扩充”部分似乎提供了解决方案:

https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

In your case, if class A is exported from file1.ts , and you want to add methodY() to that class within a different module file2.ts ,然后试试这个:

 //// file1.ts
export class A extends B {
    constructor(...);
    methodX(): void;
}

//// file2.ts
import { A } from "./file1";
declare module "./file1" {
    interface A {
        methodY(): void;
    }
}
A.prototype.methodY = function() {}

原文由 Serban Stokker 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题