Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typed methods in TypeScript

Tags:

typescript

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.

like image 340
Jacob Rask Avatar asked Jun 19 '26 18:06

Jacob Rask


1 Answers

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.

like image 143
bert Avatar answered Jun 21 '26 13:06

bert