Unidentified class in Typescript

Does anyone know how to create an anonymous class in TypeScript?

Here is my code:

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

I'm attempting to achieve something like this:

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

Can anyone guide me on how to accomplish this?

Answer №1

Sure, I can show you the solution.

Let's start with the abstract class:

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

Now, here is an example of an anonymous implementation:

const runnable = new class extends Runnable {
  run() {
    // Your implementation goes here
  }
}();

Answer №2

Not quite there yet, but here's a workaround:

abstract class Runnable {
    public abstract run();
}

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

runnable.run(); // running...

(Try it out in the playground)

The downside of this method is that the interpreter will reevaluate the class every time it's used, unlike with compiled languages like Java where the compiler only evaluates it once.

Answer №3

Guide on Creating an Anonymous Class

If you have an interface called Runnable and an abstract class named Task, creating an anonymous class in TypeScript involves generating a class instance of Foo along with a constructor function for the same. To delve deeper into this concept, refer to the relevant TypeScript documentation. An anonymous class is essentially referred to as a constructor function resembling {new(...args):type}, which can be instantiated using the new keyword.

interface Runnable {
    run(): void;
}

abstract class Task {
    constructor(readonly name: string) {
    }

    abstract run(): void;
}

Creating an Anonymous Class Extending Superclass via class extends ?

test('Anonymous class extending superclass through `class extends ?`', () => {
    let stub = jest.fn();
    let AntTask: {new(name: string): Task} = class extends Task {
        //An anonymous class automatically inherits its superclass constructor if not explicitly declared here.
        run() {
            stub();
        }
    };

    let antTask: Task = new AntTask("ant");
    antTask.run();

    expect(stub).toHaveBeenCalled();
    expect(antTask instanceof Task).toBe(true);
    expect(antTask.name).toBe("ant");
});

Create Anonymous Class Implementing Interface/Type via class ?.

test('Anonymous class implementing interface through `class ?`', () => {
    let stub = jest.fn();
    let TestRunner: {new(): Runnable} = class {
        run = stub
    };

    let runner: Runnable = new TestRunner();
    runner.run();

    expect(stub).toHaveBeenCalled();
});

Answer №4

To achieve this, simply create an inline local class and immediately extend it:

interface Executable {
    execute();
}

// ...

const executable = new (class ___Executable implements Executable {
    execute() { /*...*/ }
});

/* Note: parentheses are not mandatory */

return new class ___Executable implements Executable {
    execute() { /*...*/ }
}

/* Rest assured, ___Executable remains within its hidden scope and does not leak into the main scope. */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

Compiling TypeScript on save disrupts AngularJS functionality in Visual Studio 2017

I am currently working on a project in Visual Studio Community 2017 (15.2) that involves AngularJS 1.6.5 and a NancyFX server. You can find the code for this project here: https://github.com/GusBeare/NancyAngularTests This project serves as a learning pl ...

The 'data-intro' property cannot be bound to the button element as it is not recognized as a valid property

I've been using the intro.js library in Angular 8 and so far everything has been working smoothly. However, I've hit a roadblock on this particular step. I'm struggling to bind a value in the data-intro attribute of this button tag. The text ...

The TypeScript error message is saying that it cannot find the property 'push' of an undefined value, resulting in a error within the

Issue: Unable to access property 'push' of undefined in [null]. class B implements OnInit { messageArr: string[]; ngOnInit() { for(let i=0; i<5; i++) { this.messageArr.push("bbb"); } } } ...

Want to learn how to integrate React-pdf (@react-pdf/renderer) with TypeScript on NodeJS and Express JS?

I am encountering difficulties running React-Pdf (@react-pdf/renderer) with TypeScript on an Express JS server. I have attempted to use babel but encountered errors that I cannot resolve. build error error error You can find the Github repository for t ...

Error: The method "next" cannot be used with BehaviorSubject

My goal is to share data between sibling components by utilizing a shared service. The first component loads and retrieves a list of Servers from the API, populating a select box with all the servers. I now need to notify the other component when the user ...

Issues with the md-radio-button not functioning properly in Angular 2

I'm in need of two radio buttons to choose between two options. Here's the code I'm using: <md-radio-button [value]=true [(ngModel)]="carSelected" name="carOption">Car</md-radio-button> <md-radio-button [value]=false [(ngMode ...

Different categories of "areas" found in TypeScript within Visual Studio 2013

In C#, we often use "regions," but unfortunately that feature is missing in TypeScript. Is there a way to group code sections in TypeScript? I came across this article on Stack Overflow discussing the absence of regions in TypeScript. I'm curious if ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

The limitations of Typescript types influence the program's behavior

As a newcomer to the Typescript environment, I am currently developing a test application to familiarize myself with it. However, I have encountered an issue regarding type restrictions that seems to be not working as expected. In my class, I have defined ...

A method for handling specific subsets of an enum in a secure and controlled manner

I have an enumerated type called Country and another type that represents a subset of European countries. I want to handle values within this subset differently from others. Currently, I am using an if statement with multiple conditions, but it could get u ...

Is it possible to turn off the differentiation between null and undefined in TypeScript strict null-checking mode?

I've been in the process of upgrading a large TypeScript codebase to enforce strict null-checks. This codebase contains numerous types with optional properties: interface MyInterface { member1?: number; member2?: string; } Additionally, it define ...

Exploring the method for obtaining parameters from a generic constructor

I have a customized class called Collection, which takes another class as a parameter named personClass. I expect the method add to accept parameters that are used in the constructor of the class User class Person { constructor(public data: object) { } ...

What could be causing the availability of a response in a service, but showing as undefined in the component?

Currently, I am facing a problem with my service and component setup. While the service can successfully read the response as a JSON object, the component is returning res: undefined. service: constructor( private http: Http, private fbuilder: Fo ...

Can you divide and repurpose several function overloads in TypeScript?

I've put together this sandbox of code In my project, there are 2 functions named slice in separate classes. They both contain a lengthy and repetitive set of overrides: export class Atom<S> { constructor(private initial: S) { } // Se ...

Error encountered during conversion from JavaScript to TypeScript

I am currently in the process of converting JavaScript to TypeScript and I've encountered the following error: Type '(props: PropsWithChildren) => (any[] | ((e: any) => void))[]' is not assignable to type 'FC'. Type '(a ...

The problem with the onClick event not triggering in Angular buttons

My issue revolves around a button in my code that is supposed to trigger a function logging the user out. However, for some reason, the event associated with it doesn't seem to be functioning at all. Here's the relevant code snippet: TS File: imp ...

Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema. In the past, I have created middlewares for JWT validation without passing any parameters, and they wor ...

The React state remains stagnant and does not receive any updates

Although there have been numerous questions on this topic before, each one seems to be unique and I haven't found a close match to my specific issue. In my scenario, I have a grid containing draggable ItemComponents. When an item is selected, additio ...