Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript anonymous class

Tags:

typescript

Is there a way in typescript to create anonymous class?

my code:

export abstract class Runnable {     public abstract run(); } 

and I'm trying to do something like this:

new Runnable {     runner() {         //implement     } } 

How can I do it?

like image 613
user1137582 Avatar asked Mar 13 '17 15:03

user1137582


People also ask

How do I create an anonymous class in typescript?

when you declare a class Foo in typescript you actual create an class instance of Foo & a constructor function for the class Foo . you could want to see depth in typescript. Anonymous class that ref as a constructor function like {new(... args):type} that can be created using new keyword.

What is anonymous function in typescript?

TypeScript Anonymous Functions are functions that are not bound to an identifier i.e., anonymous functions do not have name of the function. Anonymous functions are used as inline functions. These are used when the function is used only once and does not require a name. The best example is a callback function.

How do you use anonymous class?

Anonymous classes usually extend subclasses or implement interfaces. The above code creates an object, object1 , of an anonymous class at runtime. Note: Anonymous classes are defined inside an expression. So, the semicolon is used at the end of anonymous classes to indicate the end of the expression.

Why do we use anonymous class?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.


2 Answers

Yes, here is the way.

The abstract class:

export abstract class Runnable {   public abstract run(); } 

An anonymous implementation:

const runnable = new class extends Runnable {   run() {     // implement here   } }(); 
like image 134
Michal Avatar answered Sep 28 '22 03:09

Michal


Not quite, but you can do this:

abstract class Runnable {     public abstract run(); }  let runnable = new (class MyRunnable extends Runnable {     run() {         console.log("running...");     } })();  runnable.run(); // running... 

(code in playground)

The problem with this approach however is that the interpreter will evaluate the class every time it uses it, unlike with a compiled language (such as java) in which the compiler only evaluates it once.

like image 25
Nitzan Tomer Avatar answered Sep 28 '22 02:09

Nitzan Tomer