Typed Methods in TypeScript
How do I determine 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 will make it easier for me to override the method in subclasses, knowing that the methods must conform to the Listener interface.
+3
source to share
2 answers
If you want to make sure that only objects are passed to, for example, a function that "has" 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 it helps.
+2
source to share