iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Abstract Classes

An abstract class can't be instantiated directly. Subclasses must fill in any abstract members — useful when several types share behaviour but need their own implementation of one or two methods.

Shape

TS
abstract class Shape {
    abstract area(): number;

    describe(): string {
        return `area=${this.area().toFixed(2)}`;
    }
}

class Circle extends Shape {
    constructor(public r: number) { super(); }
    area() { return Math.PI * this.r ** 2; }
}

class Rectangle extends Shape {
    constructor(public w: number, public h: number) { super(); }
    area() { return this.w * this.h; }
}

console.log(new Circle(5).describe());
console.log(new Rectangle(3, 4).describe());

// new Shape();   // ✗ error — cannot instantiate abstract class

Abstract members

  • Methods — declared with abstract and no body.
  • Properties — declared with abstract and no initializer.
  • Accessors — abstract getters and setters too (4.6+).
TS
abstract class Account {
    abstract readonly type: 'checking' | 'savings';
    abstract get balance(): number;
}

Abstract vs interface

Abstract classInterface
Can hold state and concrete code.No state, only signatures (mostly).
Single inheritance.Class implements many.
"Template method" pattern — shared scaffolding.Pure capability contract.
Live in the JS output (real class).Erased at runtime.

When to reach for one

  • Several subclasses share substantial code and need to fill in a piece each.
  • You want a callable factory or fluent base class — but be cautious; composition often beats inheritance.
Tip: Don't reach for abstract classes too early. The moment a "template method" gets complex, refactor to composition with injected strategies — easier to test, easier to swap.

Example

Example
abstract class Shape {
  abstract area(): number;
  describe() { return `area=${this.area().toFixed(2)}`; }
}
class Circle extends Shape {
  constructor(public r: number) { super(); }
  area() { return Math.PI * this.r ** 2; }
}
console.log(new Circle(5).describe());
Try it Yourself »

Exercise

Keyword for a class that can't be instantiated.

class Shape {}

Test yourself

Q1. Abstract classes are…
Q2. Abstract methods have…
Q3. Abstract classes survive at runtime as…

Discussion

Loading…