Abstract classes in TypeScript
A base that cannot be instantiated, with members a subclass must supply.
interface Describable {
describe(): string;
}
abstract class Check implements Describable {
abstract readonly name: string;
abstract passes(value: string): boolean;
describe(): string {
return `${this.name} check`;
}
report(value: string): string {
return `${this.describe()}: ${this.passes(value) ? "pass" : "fail"}`;
}
}
class MinLength extends Check {
readonly name = "min length";
constructor(private floor: number) {
super();
}
passes(value: string): boolean {
return value.length >= this.floor;
}
}
const checks: Check[] = [new MinLength(3)];
console.log(checks.map((check) => check.report("ada")));
How it works
abstractmembers have no body and must be implemented.- The base can still hold shared, concrete behavior.
implementschecks a class against an interface.
Keywords and builtins used here
Checkabstractbooleanclassconstconstructorextendsimplementsinterfacenumberprivatereadonlyreturnstringsuperthis
The run, in numbers
- Lines
- 29
- Characters to type
- 610
- Tokens
- 163
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 98 seconds.
Step 3 of 4 in Classes, step 3 of 19 in Classes & patterns.