2016-08-19 9 views
0
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 prototypeをES6に拡張したいと思っていました。このコードはTypeScript Playgroundでうまく機能しますが、lib.es6.d.tsのFunction定義とマージできないため、tsc 1.8.10では(プロパティ<<name>>はタイプ 'Function'には存在しません)失敗します。TypeScript merge関数のインタフェース、extend関数プロトタイプ

どのように正しく行うにはどのようなアイデアですか? docsによれば

答えて

1

同様に、グローバルスコープは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 
+0

その後TSCは、コールのようなメソッドを参照して適用されません、lib.es6.d.ts.で宣言された基本的にすべてのもの私はそれらの定義をマージしたいと思います。 – m1gu3l

+0

私の作品を確認した私の編集を参照してください。 –

+0

src/utils/Function.augment.ts(13,15):エラーTS2339: '関数'の型に 'call'プロパティが存在しません。 – m1gu3l

関連する問題