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)();
I wanted to do bad thing and extend Function prototype in TypeScript compiling to ES6. While this code works well in TypeScript Playground it fails in tsc 1.8.10 (Property <<name>>
does not exist on type 'Function') because it can't merge with Function definition in lib.es6.d.ts .
Any ideas how to do it properly?
According to the docs :
Similarly, the global scope can be augmented from modules using a
declare global
declaration.
Note the wording from modules . In other words, put the augmentations in a different module, and import it, which is when the merging occurs. Also, put the new prototype definitions in the same file.
// 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)();
Output:
f1
f2
f3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.