Cri*_*ine 3 javascript module typescript typescript1.8
我想从模块内向 Typescript (1.8) 中的数组原型添加一个函数。
我正在更改 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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在我的 main.ts 文件中全局应用该更改,如下所示:
import {Array<T>.remove} from "./utils.ts"
let arr = ["an", "array"];
arr.remove("array");
Run Code Online (Sandbox Code Playgroud)
我可以导入接口声明,但对 Array 原型的更改在 main.ts 文件中不可用。如何对原型进行更改并将其全局应用或以某种方式导入“删除”功能?
这对我有用:
测试.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);
}
}
Run Code Online (Sandbox Code Playgroud)
测试2.ts:
import "./test";
let arr = ["an", "array"];
arr.remove("array");
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
编译并运行:
tsc -m "commonjs" ./test2.ts
node ./test2.js
Run Code Online (Sandbox Code Playgroud)
输出:
[ 'an' ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
683 次 |
| 最近记录: |