How to create Anonymous Class?
Let's say you have a interface Runnable and an abstract class Task.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.
interface Runnable {
run(): void;
}
abstract class Task {
constructor(readonly name: string) {
}
abstract run(): void;
}
Create anonymous class extends superclass via class extends ?
test('anonymous class extends superclass by `class extends ?`', () => {
let stub = jest.fn();
let AntTask: {new(name: string): Task} = class extends Task {
//anonymous class auto inherit its superclass constructor if you don't declare a constructor 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 implements interface/type via class ?.
test('anonymous class implements interface by `class ?`', () => {
let stub = jest.fn();
let TestRunner: {new(): Runnable} = class {
run = stub
};
let runner: Runnable = new TestRunner();
runner.run();
expect(stub).toHaveBeenCalled();
});
const myRunnable = <Runnable>{ run:() => { console.log("I ran"); } }But I think this is more like typecasting, not inheritance