Extending vs. implementing a pure abstract class in TypeScript

Viewed 47178

Suppose I have a pure abstract class (that is, an abstract class without any implementation):

abstract class A {
    abstract m(): void;
}

Like in C# and Java, I can extend the abstract class:

class B extends A {
    m(): void { }
}

But unlike in C# and Java, I can also implement the abstract class:

class C implements A {
    m(): void { }
}

How do classes B and C behave differently? Why would I choose one versus the other?

(Currently, the TypeScript handbook and language specification don't cover abstract classes.)

5 Answers

Building on @toskv's answer, if you extend an abstract class, you have to call super() in the subclass's constructor. If you implement the abstract class, you don't have to call super() (but you have to implement all the methods declared in the abstract class, including private methods).

Implementing an abstract class instead of extending it could be useful if you want to create a mock class for testing without having to worry about the original class's dependencies and constructor.

i've found that using a pure abstract class ( A ) and then using implements seems to be a way to annotate information about the access privileges that you might want to force in the contract, but Interfaces or base class extending doesn't

For example, this works for me ( excerpt from a Svelte-Kit program for reference only )

abstract class AudioEngine {
    protected static ctx: AudioContext;
    protected static setState(s: string) { };
}

class Elementary implements AudioEngine {

constructor(ctx: AudioContext) {
    this.ctx = ctx;
};

ctx: AudioContext

protected setState(newState: string) {
        this.status.set(Sound[newState])
        return this.getState()
    };
Related