Template-style class hierarchies
A family of domain objects shares behavior but must provide different operations.
TypeScript · Const
TypeScript’s abstract modifier defines base classes and members that require subclass implementations. Abstract classes cannot be instantiated directly, but they can combine shared implementations with enforced subclass contracts.
Use the abstract modifier to define a class intended only as a base for subclasses. Abstract members declare required contracts without implementations; concrete subclasses must implement them before they can be instantiated.
abstract class ClassName {
abstract memberName: Type;
abstract methodName(...args: Args): ReturnType;
}abstract class Repository<T> {
abstract findById(id: string): Promise<T | undefined>;
log(result: T | undefined): void {
console.log(result);
}
}
class UserRepository extends Repository<User> {
async findById(id: string): Promise<User | undefined> {
return id === "u1" ? { id, name: "Ada" } : undefined;
}
}
type User = { id: string; name: string };
const repository = new UserRepository();
repository.log(await repository.findById("u1"));A concrete subclass implements the required abstract method while inheriting the base implementation.
A family of domain objects shares behavior but must provide different operations.
A framework needs to require lifecycle or data-access methods from integrations.
Common logging, validation, or state belongs in one reusable superclass.
An abstract class is a base class that cannot be instantiated directly. It can contain implemented members plus abstract members that subclasses must provide.
Follow-up: How does it differ from an interface? An abstract class can share implementation and state, while an interface describes a type contract without providing class implementations.
An abstract method has a signature but no body. A concrete subclass must implement it, unless that subclass remains abstract.
Follow-up: What happens if the subclass omits it? TypeScript reports an error when the subclass is concrete; marking the subclass abstract defers the requirement.
The compiler rejects new applied to an abstract class because the class is intended only to be extended. Instantiate a concrete subclass instead.
Follow-up: Can an abstract class be used as a variable type? Yes; a concrete subclass instance can be assigned to a variable typed as the abstract base class.
classextendsimplementsinterfaceabstract new construct signatures