简体   繁体   English

全局(从模块内部)向原型添加函数

[英]Add a function to a prototype globally (from within a module)

I want to add a function to the Array prototype in Typescript (1.8) from within a module. 我想从一个模块中向Typescript(1.8)中的Array原型添加一个函数。

I am altering the prototype in my utils.ts file: 我正在utils.ts文件中更改原型:

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);
    }
}

And now I would like to apply that change globally in my main.ts file somehow like this: 现在,我想以某种方式在我的main.ts文件中全局应用此更改:

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

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

I can import the interface declaration but the change to the prototype of Array is not available in the main.ts file. 我可以导入接口声明,但是在main.ts文件中没有对Array原型的更改。 How can I make a change to a prototype and apply that globally or somehow import that "remove" functionality? 如何更改原型并在全球范围内应用,或以某种方式导入该“删除”功能?

This works for me: 这对我有用:

test.ts: 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: test2.ts:

import "./test";

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

Compile and run: 编译并运行:

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

Output: 输出:

[ 'an' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM