TypeScript by Example: Classes
Object-oriented programming in TypeScript with access modifiers and inheritance patterns. This code example illustrates public, private, and protected members, class extension with the extends keyword, constructor chaining with super, and method overriding for specialized behavior.
Code
class Animal {
// Access modifiers: public, private, protected
private name: string;
constructor(theName: string) {
this.name = theName;
}
public move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name);
}
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
sam.move();
// console.log(sam.name); // Error: 'name' is privateExplanation
TypeScript offers full support for class-based object-oriented programming. It adds access modifiers like public, private, and protected to control the visibility of class members. By default, members are public.
private members cannot be accessed from outside the class. protected members act like private members but can also be accessed by deriving classes. Inheritance is achieved using the extends keyword.
Derived classes that contain constructor functions must call super() which executes the constructor of the base class. You can also override methods from the base class.
Code Breakdown
private name makes this property accessible only within the class.public move is accessible from anywhere (default modifier).extends Animal creates inheritance from the base class.super(name) calls the parent class constructor.
