从 Typescript 中的另一个文件向 class 添加函数

Add function to class from another file in Typescript

我想知道是否有可能在 Typescript 的 class 原型中添加一些函数。

我的情况是这样的: 我有一个带有 class 的文件,例如image.ts:

export class Image {
    b64img: string;
}

此 class 已生成,因此我无法向其添加方法。我在其他生成的 classes 中使用此 class,因此创建一个带有扩展图像的新 class 无法添加功能。

是否有任何选项可以让我在单独的文件中向我的 class 添加函数,以便我可以在 class 图像的所有对象上使用它?

谢谢

可以。您可以通过为定义它的模块定义扩展来扩展它。

创建一个名为 image-extension.ts 或类似名称的文件。

现在,如果在该文件中您将像这样导入 Image

import { Image } from `image`;

declare module 'image' { // same name than in the import!
    export interface Image {
         newMethod: () => void;
    }
}

Image.prototype.newMethod = function() {
    console.log('new method');
}

现在,无论您将此文件导入何处,都可以使用该方法:

import { Image } from 'image';
import 'image-extension'; // import just for side-effects

当然,您也可以将 declare module 添加到 d.ts 文件中,这样它会自动加载,并在另一个文件中将真正的函数添加到原型中,确保这样一个文件已加载到您的应用程序中