【问题标题】:TypeScript merge Function interface, extend Function prototypeTypeScript 合并 Function 接口,扩展 Function 原型
【发布时间】:2016-12-26 11:04:48
【问题描述】:
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 中失败(属性<<name>> 不存在于类型'Function'),因为它无法与lib.es6.d.ts 中的函数定义合并。

任何想法如何正确地做到这一点?

【问题讨论】:

    标签: javascript function typescript ecmascript-6 prototype


    【解决方案1】:

    根据docs

    同样,可以使用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
    

    【讨论】:

    • 然后 tsc 看不到 call 和 apply 之类的方法,基本上是 lib.es6.d.ts 中声明的所有内容。我想合并这些定义。
    • src/utils/Function.augment.ts(13,15):错误 TS2339:“函数”类型上不存在属性“调用”。
    猜你喜欢
    • 2017-03-04
    • 2018-04-09
    • 1970-01-01
    • 2019-05-01
    • 2021-08-07
    • 2015-04-01
    • 2022-12-06
    • 1970-01-01
    相关资源
    最近更新 更多