TypeScript
Interfaces & Inheritance
Interface for Classes
implements checks that a class has everything an interface describes:
interface IUser {
id: number;
name: string;
age?: number;
register(): string;
}
class User implements IUser {
// Properties
id: number;
name: string;
age?: number; // Optional property
// Constructor - called during object instantiation
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
// Methods
register() {
return `${this.name} is now registered`;
}
// Static members (properties or methods that belong to the class itself, not to instances of the class)
static count: number = 0;
}
A class can implement several interfaces: class User implements IUser, Serializable.
Inheritance (Extend Classes)
// Base Class: User
class User {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return `Hello, ${this.name}`;
}
}
// Subclass: Admin extends User
class Admin extends User {
role: string;
constructor(name: string, role: string) {
super(name); // Call base class constructor
this.role = role;
}
getRole() {
return `${this.name} is an ${this.role}`;
}
}
const admin = new Admin("Pirate Dev", "owner");
admin.greet(); // inherited from User
admin.getRole(); // "Pirate Dev is an owner"
A subclass constructor must call super(...) before it uses this.
Overriding Methods
A subclass can replace a method of its base class. The override keyword makes the intent explicit: TypeScript reports an error if the base class has no such method (for example after a rename). With the noImplicitOverride option, override becomes required on every overriding method.
class Admin extends User {
override greet() {
return `Welcome back, ${this.name}`;
}
}
Abstract Classes
An abstract class can't be created with new; it exists only to be extended. Its abstract members have no body and must be implemented by every subclass:
abstract class Shape {
abstract area(): number;
describe() {
return `Area: ${this.area()}`;
}
}
class Square extends Shape {
constructor(private size: number) {
super();
}
area() {
return this.size ** 2;
}
}
new Shape(); // Error: Cannot create an instance of an abstract class
new Square(3).describe(); // "Area: 9"
| Use | When |
|---|---|
interface | Only describes a shape. No code, nothing at runtime. |
abstract class | Shares real code between subclasses and forces some methods. |
