AI Hints
Home›TypeScript Tutorial›Classes and Contracts
TypeScript · Lesson 48 of 120

Abstract Classes

Must be finished.

⏱ 2 min read▶ Video at 38:04🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

An abstract class is a half finished class. It can't be created directly. It provides some shared code, and lists abstract methods that each subclass must write.

Abstract Classes
From the video: Abstract Classes
  • Half finished
  • Can't be created
  • Subclasses finish it

A report base class

Report is abstract. It has a shared print method, but its body method is abstract. Sales report fills in the body. Run it.

app.tstypescript
abstract class Report {
  constructor(protected title: string) {}
  abstract body(): string;
  print(): void {
    console.log(`== ${this.title} ==`);
    console.log(this.body());
  }
}

class SalesReport extends Report {
  constructor(private total: number) { super("Sales"); }
  body() { return `Total sales: £${this.total}`; }
}

new SalesReport(4820).print();
Output
== Sales ==
Total sales: £4820

Cannot create it directly

Making a report directly is not allowed, because its body is unfinished. Run it.

app.tstypescript
abstract class Report {
  abstract body(): string;
}
const r = new Report();
Output
app.ts line 4: Cannot create an instance of an abstract class.

Summary

Abstract classes share code, and force subclasses to finish the abstract methods. Next, static members.

Key takeaways
  • abstract class
  • abstract body()
  • Subclass finishes
Next up: Static Members — on the class