Is it possible to specify that a class implements an abstract class after declaration?

99 Views Asked by At

I would like to declare an abstract class and a class without declaring that the class implements the abstract class in the same file.

abstract class ExampleAbstractClass {
    abstract exampleMethod(): string;
}

class ExampleClass {
    exampleMethod(): string { return 'test'; }
}


// I would like to specify that the class does implement the abstract class in another file
ExampleClass implements ExampleAbstractClass

Playground

This kind of use case is possible in other languages like Swift with protocols.

1

There are 1 best solutions below

2
On

Yes, it is possible:

example-class.ts

export abstract class ExampleAbstractClass {
    abstract exampleMethod(): string;
}

export class ExampleClass {
    exampleMethod(): string { return 'test'; }
}

export interface ExampleClass extends ExampleAbstractClass {} // NOTICE: usage of interface!

example-class.test.ts

import { ExampleClass, ExampleAbstractClass } from "./example-class";

const a: ExampleAbstractClass = new ExampleClass(); // works!
console.log(a.exampleMethod());

You'll have to use interface alongside class since class declaration merging is currently disallowed in TypeScript. You could also augment the module which defines and implements ExampleClass in separate files using declare module "<path to implementation source file>" {}.