Syntax
abstract class Name {
abstract method(): type;
}Examples
Defining and Extending an Abstract Class
Enforcing that subclasses implement specific methods, while sharing common logic.
abstract class Shape {
abstract getArea(): number; // no implementation - subclasses MUST provide one
describe(): string {
// a concrete method, shared and inherited as-is by every subclass
return `This shape has an area of ${this.getArea()}`;
}
}
// const shape = new Shape(); // Error - cannot instantiate an abstract class
class Circle extends Shape {
constructor(private radius: number) {
super();
}
getArea(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(5);
console.log(circle.describe());Best practices
- Use abstract classes when related classes should share both a common contract (abstract methods) and some actual shared implementation (concrete methods)
- Use a plain interface instead when you only need to enforce a shape/contract with no shared implementation at all
- Remember abstract classes can never be instantiated directly - attempting new AbstractClass() is always a compile error
- Keep abstract method signatures focused and minimal - the fewer methods subclasses are forced to implement, the easier the class family is to extend
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook