網站搜尋

javascript - 在 TypeScript 中向現有類別添加方法?


我正在一個 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;
}

它不起作用,有沒有人知道我如何能實現覆寫一個類或用一個新方法擴展它?

謝謝

答案#1

TypeScript 文件中「Declaration Merging > Module Augmentation」章節似乎提供了解決方案:

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

在你的情況下,如果 class A 是從 file1.ts 匯出的,並且你想在不同的模組 file2.ts 中為該類添加 methodY(),那麼可以試試這個方法:

//// 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() {}

答案#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();

我在這裡做了一個遊樂場範例。