Abstract classes
Concept and syntax
An abstract class can provide shared implementation and require derived classes to implement abstract members. It cannot be instantiated directly in checked TypeScript. A concrete subclass must fulfill the required members; use an abstract base when shared behavior and a contract are both useful.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
abstract class ShapeBase {abstract area():number;describe(){return "area="+this.area();}}class Square extends ShapeBase {constructor(public side:number){super();}area(){return this.side*this.side;}}console.log(new Square(3).describe());Expected output:
area=9Common mistake
Intentionally invalid; compile separately and do not execute.
abstract class ShapeBase {abstract area():number;}new ShapeBase();Expected diagnostic: TS2511. An abstract class cannot be instantiated directly. Construct a concrete subclass.
Practice and recap
Implement a rectangle subclass with two dimensions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Abstract classes — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
abstract class ShapeBase {abstract area():number;describe(){return "area="+this.area();}}class Square extends ShapeBase {constructor(public side:number){super();}area(){return this.side*this.side;}}console.log(new Square(3).describe());Which diagnostic and explanation match the rejected example under the lesson settings?
abstract class ShapeBase {abstract area():number;}new ShapeBase();