この単純化されたコードの元の目的は、代理人とオブジェクトを受け取るtypescriptでジェネリックメソッドを作成し、渡された委譲しますが、 "this"コンテキストはオブジェクトに渡されます。異なる数のジェネリックパラメータでオーバーロードを作成するときの問題
疑似コードとして、 f(del(args:... parameters)、context)=> del(this:typeof context、args:... parameters)のようになります。
私はいくつかのアプローチを試みましたが、すべて失敗しました。
次のコードは、最も有望だったようですが、最終的には失敗しました。
コードでは私の問題を強調しました。基本的には、typescriptコンパイラは、arg1とarg2の型を自動的にmethodWithDelegate関数のシグネチャを調べることができません。
説明はありますか?
解決策はありますか?
function createDelegate<TContext extends Object, TReturn, A>(fn: (a: A) => TReturn, context: TContext): (this: TContext, a: A) => TReturn
function createDelegate<TContext extends Object, TReturn, A, B>(fn: (a: A, b: B) => TReturn, context: TContext): (this: TContext, a: A, b: B) => TReturn
function createDelegate<TContext extends Object, TReturn, A, B, C>(fn: (a: A, b: B, c: C) => TReturn, context: TContext): (this: TContext, a: A, b: B, c: C) => TReturn
function createDelegate<TContext extends Object, TReturn, A, B, C>(instance: any, funct: Function): any
{
return <any>funct.bind(instance);
}
function methodWithDelegate(delegate: (this: string, val1: string, val2: string) => void)
{
//delegate invokation
}
methodWithDelegate(function (val1, val2)
{
// OK. val1 and val2 are inferred to be strings.
val1.substring(2);
});
methodWithDelegate(createDelegate(function (val1, val2)
{
// ISSUE: val1 and val2 are not inferred to be strings. they remain of type any
val1.substring(2);
}, "CONTEXT"));