简体   繁体   English

TypeScript合并Function接口,扩展Function原型

[英]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)();

I wanted to do bad thing and extend Function prototype in TypeScript compiling to ES6. 我想做坏事,并将TypeScript编译中的Function原型扩展到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 . 尽管此代码在TypeScript Playground中运行良好,但在tsc 1.8.10中失败(类型'Function'不存在属性<<name>> ),因为它无法与lib.es6.d.ts中的 Function定义合并。

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. 同样,可以使用declare global声明从模块扩展全局范围。

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

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

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