2016-12-29 9 views
1

私は、(別の名前を持つ)特定のインターフェイスで単一のメソッドを実装することが予想されるクラスを作成しようとしています。どのようにテンプレートメソッドをメンバメソッドとして宣言できますか?*プロパティではありませんか?

これは、TypeScriptのジェネリックスを介して機能します(下記のRpcHandlerを参照)。

ただし、TypeScriptはメンバメソッドとメンバプロパティを区別するため、プロパティとしてではなくメソッドとして実装するときにコンパイルエラーが発生します。


方法は、プロパティをRpcHandler#executeが方法であることを活字体へのヒント、そしてないためにありますか?

class Thing { } 

interface RpcActions { 
    getThing(id: string): Promise<Thing> 
} 

// --- 

class RpcHandler<ActionName extends keyof RpcActions> { 
    execute: RpcActions[ActionName]; 
} 

// --- 

class GetThingAsMethodHandler extends RpcHandler<'getThing'> { 
    // How can I declare the type of execute so that it is a member 
    // and not a property, so this doesn't error? 

    // Error: Class 'RpcHandler<"makeThing">' defines instance member 
    // property 'execute', but extended class 'MakeThingHandler' defines 
    // it as instance member function. 
    async execute(data: Object): Promise<Thing> { 
    return new Thing(); 
    } 
} 

// Workaround, for now 

class GetThingAsPropertyHandler extends RpcHandler<'getThing'> { 
    execute = async (id: string): Promise<Thing> => { 
    return new Thing(); 
    } 
} 

答えて

1

インターフェイスのメソッドとプロパティの区別はありません。メソッドはプロトタイプ上で定義され、初期化されていればプロパティはコンストラクタに割り当てられているため、クラスのために維持されているでしょう - したがって、派生クラスのプロトタイプで定義されるメソッドは、基本クラスのコンストラクタです。あなたがインターフェイスにRpcHandlerを回すことができるかどう

そう、それはほとんどことを除いて、作品executeMakeThingHandlerには、任意の引数を取ることができない:コード付き

class Thing { } 

interface RpcActions { 
    makeThing(): Promise<Thing> 
    getThing(id: string): Promise<Thing> 
} 

// --- 

interface RpcHandler<ActionName extends keyof RpcActions> { 
    execute: RpcActions[ActionName]; 
} 


// --- 

class MakeThingHandler implements RpcHandler<'makeThing'> { 

    async execute(): Promise<Thing> { 
    return new Thing(); 
    } 
} 

executedata: Object引数を持っているとき、あなたは意志をそのため

test.ts(17,7): error TS2420: Class 'MakeThingHandler' incorrectly implements interface 'RpcHandler<"makeThing">'. 
    Types of property 'execute' are incompatible. 
    Type '(data: number) => Promise<Thing>' is not assignable to type '() => Promise<Thing>'. 

可能な回避策を取得

としてRpcActionsにmakeThing()を宣言することです
makeThing(arg: any): Promise<Thing> 
+0

Ah!最後に表示されるエラーは、テンプレートタイプとして 'getThing'が必要なためです( 'makeThing'ではなく)。私は少し例をきれいにしましたが、インターフェースは私が探しているものです、ありがとう! – Nevir

関連する問題