function - 从 Typescript 中的另一个文件将函数添加到类中

标签 function typescript extension-methods

我想知道是否有可能向 Typescript 中的类原型(prototype)添加一些函数。

我的情况是这样的: 我有一个包含类的文件,例如图像.ts:

export class Image {
    b64img: string;
}

这个类是生成的,所以我无法向它添加方法。我在其他生成的类中使用此类,因此无法使用 extends Image 创建新类来添加功能。

是否有任何选项可以将函数添加到单独文件中的类中,以便我可以在类 Image 的所有对象上使用它?

谢谢

最佳答案

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

创建一个名为 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文件中,这样它就会自动加载,并在另一个文件中将真正的函数添加到原型(prototype),确保这样的文件加载到您的应用程序中

关于function - 从 Typescript 中的另一个文件将函数添加到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50155811/

相关文章:

function - Scala 中的反函数

typescript - 如何在 typescript 中处理字符串枚举与不同字符串文字的反向映射?

javascript - 类型 Promise<void> 不可分配给类型 Promise<customType[]>

typescript - 错误 MSB4064 : The "ComputeInputAndOutputOnly" parameter is not supported by the "VsTsc" task

c# - 何时使用 this 关键字作为函数参数

c# - 在 C# 中的数组上使用 Contains() 扩展方法

Python 函数——当我不知道函数需要多少个参数时如何动态调用函数?

r - 在 R 中使用 fitdist 时出错 - 必须定义 dllogis 函数

php - 页面加载后javascript函数不工作

c# - 如何使用 lambda 表达式创建扩展方法