全局(从模块内部)向原型添加函数 [英] Add a function to a prototype globally (from within a module)

查看:107
本文介绍了全局(从模块内部)向原型添加函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个模块中向Typescript(1.8)中的Array原型添加一个函数.

I want to add a function to the Array prototype in Typescript (1.8) from within a module.

我正在更改utils.ts文件中的原型:

I am altering the prototype in my utils.ts file:

declare global {
    interface Array<T> {
        remove(obj: any): void;
    }
}

Array.prototype.remove = function(obj) {
    var idx = this.indexOf(obj);
    if (idx > -1) {
        this.splice(idx, 1);
    }
}

现在我想以某种方式在我的main.ts文件中全局应用此更改:

And now I would like to apply that change globally in my main.ts file somehow like this:

import {Array<T>.remove} from "./utils.ts"

let arr = ["an", "array"];
arr.remove("array");

我可以导入接口声明,但是对Array原型的更改在main.ts文件中不可用.如何更改原型并在全球范围内应用,或以某种方式导入该删除"功能?

I can import the interface declaration but the change to the prototype of Array is not available in the main.ts file. How can I make a change to a prototype and apply that globally or somehow import that "remove" functionality?

推荐答案

这对我有用:

test.ts:

export {};

declare global {
    interface Array<T> {
        remove(obj: any): void;
    }
}

Array.prototype.remove = function(obj) {
    var idx = this.indexOf(obj);
    if (idx > -1) {
        this.splice(idx, 1);
    }
}

test2.ts:

import "./test";

let arr = ["an", "array"];
arr.remove("array");
console.log(arr);

编译并运行:

tsc -m "commonjs" ./test2.ts
node ./test2.js

输出:

[ 'an' ]

这篇关于全局(从模块内部)向原型添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆