[英]TypeScript merge Function interface, extend Function prototype
interface Function {
next(next: Function): Function;
prev(prev: Function): Function;
}
Function.prototype.next = function(next) {
const prev = this;
return function() {
return next.call(this, prev.apply(this, arguments));
};
};
Function.prototype.prev = function(prev) {
const next = this;
return function() {
return next.call(this, prev.apply(this, arguments));
};
};
const f1 = function() { console.log("f1"); };
const f2 = () => console.log("f2");
const f3 = new Function("console.log('f3');");
f1.next(f2).next(f3)();
我想做壞事,並將TypeScript編譯中的Function原型擴展到ES6。 盡管此代碼在TypeScript Playground中運行良好,但在tsc 1.8.10中失敗(類型'Function'不存在屬性<<name>>
),因為它無法與lib.es6.d.ts中的 Function定義合並。
任何想法如何正確地做到這一點?
根據文檔 :
同樣,可以使用
declare global
聲明從模塊擴展全局范圍。
注意模塊中的措辭。 換句話說,將擴充放入不同的模塊中,然后將其導入(即合並發生時)。 另外,將新的原型定義放在同一文件中。
// augment.ts
export {};
declare global {
interface Function {
next(next: Function): Function;
prev(prev: Function): Function;
}
}
Function.prototype.next = function(next) {
const prev = this;
return function() {
return next.call(this, prev.apply(this, arguments));
};
};
Function.prototype.prev = function(prev) {
const next = this;
return function() {
return next.call(this, prev.apply(this, arguments));
};
};
// test.ts
import './augment';
const f1 = function() { console.log("f1"); };
const f2 = () => console.log("f2");
const f3 = new Function("console.log('f3');");
f1.next(f2).next(f3)();
輸出:
f1
f2
f3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.