Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous class in Typescript

Tags:

typescript

Getting some trouble to do the following in typescript. I've the following interface defined :

 interface RendererCallback {

        getNode():HTMLElement;

        getTable();
 }

There is a method expecting a RenderCallback object like :

render( callback:RendererCallback ) 

How do I create an anonymous instance in the middle of my code :

myObject.render( new .. {
  getNode() {
    return myNode;
  }
  getTable() {
    .. some code...
    return something;
  }
 } );
like image 338
ic3 Avatar asked Nov 19 '13 13:11

ic3


2 Answers

You can use anonymous objects and lambdas:

myObject.render({
    getNode: () => { doSomething...; return myNode },
    getTable: () => myTable
});

Note, the new keyword is not used.

like image 103
MgSam Avatar answered Sep 19 '22 00:09

MgSam


Typescript now supports class expressions so you can make actual anonymous classes.

myObject.render( new class {
  getNode() {
    return myNode;
  }
  getTable() {
    .. some code...
    return something;
  }
 } );

This has the benefit of this not being inferred to be any within the anonymous class' methods.

like image 40
stuffins Avatar answered Sep 22 '22 00:09

stuffins