Abstract Classes
Shared base behavior with abstract methods subclasses must implement.
14 minLevel 13 of 20
Abstract classes
An abstract class can provide shared implementation and declare abstract methods subclasses must implement. You cannot new an abstract class directly.
Abstract base
abstract class Worker {
constructor(public name: string) {}
report() { return this.name + ": " + this.work(); }
abstract work(): string;
}
class Coder extends Worker {
work() { return "coding"; }
}
console.log(new Coder("Ada").report());Abstract vs interface
Use an interface for a pure contract. Use an abstract class when you need shared code + forced hooks. Nest rarely requires abstract classes, but they help for template-method style pipelines.
Template method
abstract class IngestJob {
run() {
const raw = this.fetch();
return this.parse(raw);
}
abstract fetch(): string;
abstract parse(raw: string): string[];
}
class CsvJob extends IngestJob {
fetch() { return "a,b,c"; }
parse(raw: string) { return raw.split(","); }
}
console.log(new CsvJob().run());Nest note
Prefer interfaces + composition for Nest providers. Reach for abstract classes when multiple providers share substantial algorithm structure.
Shared helper
abstract class BaseRepo {
protected mapRow(row: { id: string }) { return row.id; }
}
class UserRepo extends BaseRepo {
toId(row: { id: string }) { return this.mapRow(row); }
}
console.log(new UserRepo().toId({ id: "u1" }));Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice