How do I define the type of a class method in TypeScript? For a regular function, I would do
interface Listener { (foo: string, bar: any): void; }
// foo and bar will be typed according to the Listener interface
let listener: Listener = function(foo, bar) { };
Is it possible to declare a method with the Listener interface?
class Foo {
// will warn about implicit 'any' types
listener1(foo, bar) { }
// I want to avoid this
listener2(foo: string, bar: any): void { }
}
This would make it easier for me to override the method in subclasses, knowing that the methods need to conform to the Listener interface.
If you want to make sure that only objects are passed into for example a function that "have" a listener function you can also use an interface.
interface IListener{
listener(type: string, payload: any):void
}
function somethingElse( l:IListener ){
l.listener( "hello", "heavy payload" );
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With