2016-09-29 7 views
0

ノードを拡張するクラスがあります。EventEmitterしかし、私は登録できるイベントを制限したい。typescriptで継承したメソッドのパラメータを制限できますか?

class Foo extends EventEmitter { 
    on(event: 'myEvent', listener: Function): this; 
    emit(event: 'myEvent', ...args: any[]): boolean 
} 
var foo = new Foo(); 
foo.on('wrongEvent',()=>{}); // this should cause compiling error 

これは実現可能ですか?

私はエラーを取得しています:

t.ts(6,3): error TS2391: Function implementation is missing or not immediately following the declaration. 
t.ts(7,3): error TS2391: Function implementation is missing or not immediately following the declaration. 
t.ts(10,8): error TS2345: Argument of type '"wrongEvent"' is not assignable to parameter of type '"myEvent"'. 

にはどうすればTS2391エラーを防ぐことができますか?

+0

TS2391はただ実装が欠落していることを述べているので、それを実装します。 –

+0

制限パラメータのタイプについては、[文字列リテラルタイプ](https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types) –

+0

@AlekseyLを試すことができます。ありがとう!この場合、親クラスの実装を使用したいと思います。それは可能ですか? – zjk

答えて

0

私は自分自身@ AlekseyLに応じてこれをお答えします。さんのコメント

class Foo extends EventEmitter { 
    on(event: 'myEvent', listener: Function): this { 
    return super.on(event, listener); 
    }; 
    emit(event: 'myEvent'): boolean { 
    return super.emit(event); 
    } 
} 
関連する問題