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?
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.
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.
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.
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.
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 } }();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With