【问题标题】:Add a function to a prototype globally (from within a module)将函数全局添加到原型(从模块内)
【发布时间】:2023-03-26 21:33:02
【问题描述】:

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

我正在修改 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);
    }
}

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

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

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

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

【问题讨论】:

    标签: javascript typescript module typescript1.8


    【解决方案1】:

    这对我有用:

    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' ]
    

    【讨论】:

    • 非常感谢。像魅力一样工作:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    相关资源
    最近更新 更多