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