7

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;
  }
 } );
0

4 Answers 4

9

You can use anonymous objects and lambdas:

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

Note, the new keyword is not used.

Sign up to request clarification or add additional context in comments.

1 Comment

You beat me to it, but yes, those actually are functions in my original answer. The return statement is implicit for single-expression lambdas without brackets. It's equivalent to this in vanilla JavaScript: getNode: function() { return myNode; }
6

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.

1 Comment

The full syntax for typed anonymous classes is new class implements MyInterface or new class extends MyClass { } (constructorArgs)
2

Here's a full code sample that works:

 interface RendererCallback {

        getNode():HTMLElement;

        getTable();
 }

 class thing {
     render(callback: RendererCallback) {

     }
 }

 var myObject = new thing();

 myObject.render(  {
    getNode() {
        return null;
    },

    getTable() {

    }


    } 
 );

Comments

0

I find it to nice to declare it like this:

propertyName: RendererCallback = {
  getNode: () => myNode, // no braces needed to only return something
  getTable() => {
    .. some code...
    return something;
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.