Skip to main content

TypeScript: Classes

Classes

In TypeScript, classes provide a blueprint for creating objects with properties and methods. They are a core feature of object-oriented programming (OOP) and are used to encapsulate data and behavior within a single construct. TypeScript enhances classes with features like type annotations, access modifiers, and abstract classes.

Constructor Params

The constructor method is a special method used for creating and initializing objects created with a class. In TypeScript, you can specify the types of the constructor parameters to ensure type safety.

class Person {
name: string;
age: number;

constructor(name: string, age: number) {
this.name = name;
this.age = age;
}

greet(): void {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old.`
);
}
}

let person = new Person("Alice", 30);
person.greet(); // Outputs: Hello, my name is Alice and I am 30 years old.

Constructor Overloading

TypeScript does not support multiple constructors directly, but you can achieve similar functionality by using optional parameters or union types.

class Point {
x: number;
y: number;

constructor(x: number);
constructor(x: number, y: number);
constructor(x: number, y?: number) {
this.x = x;
this.y = y !== undefined ? y : 0;
}

print() {
console.log(`Point (${this.x}, ${this.y})`);
}
}

let point1 = new Point(5);
let point2 = new Point(10, 15);
point1.print(); // Outputs: Point (5, 0)
point2.print(); // Outputs: Point (10, 15)

another example

class Point {
// Overloads
constructor(x: number, y: string);
constructor(s: string);
constructor(xs: any, y?: any) {
// TBD
}
}

Access Modifiers

Access modifiers control the visibility of class members. TypeScript provides three access modifiers: public, private, and protected.

  • public: This is the default access modifier. Properties and methods declared as public can be accessed from anywhere, both inside and outside the class.
  • private: Properties and methods declared as private can only be accessed within the same class. They are not accessible from outside the class.
  • protected: Properties and methods declared as protected can be accessed within the class and its subclasses. They are not accessible from outside the class and its subclasses.
class Employee {
public name: string;
private salary: number;
protected department: string;

constructor(name: string, salary: number, department: string) {
this.name = name;
this.salary = salary;
this.department = department;
}

public getDetails() {
return `${this.name} works in ${this.department} department.`;
}

private getSalary() {
return this.salary;
}

protected getDepartment() {
return this.department;
}
}

class Manager extends Employee {
constructor(name: string, salary: number, department: string) {
super(name, salary, department);
}

getManagerDetails() {
return `${this.name} manages the ${this.getDepartment()} department.`;
}
}

let employee = new Employee("John", 50000, "HR");
console.log(employee.getDetails()); // Outputs: John works in HR department.

let manager = new Manager("Alice", 70000, "IT");
console.log(manager.getManagerDetails()); // Outputs: Alice manages the IT department.
info

I've highlighted the super keyword in the Manager class constructor for clarification.

The super keyword is used to call the constructor of the superclass. In TypeScript, when a class extends another class and has a constructor, the constructor of the derived class must call super before accessing this.

This is because the base class constructor needs to complete its initialization before the derived class can start adding its own properties or methods.

Abstract Classes

Abstract classes are classes that cannot be instantiated directly. They are used as base classes for other classes to extend and implement their abstract methods.

abstract class Animal {
abstract makeSound(): void;

move() {
console.log("Moving...");
}
}

class Dog extends Animal {
makeSound() {
console.log("Bark");
}
}

let dog = new Dog();
dog.makeSound(); // Outputs: Bark
dog.move(); // Outputs: Moving...

Inheritance vs Polymorphism

Inheritance

Inheritance allows a class to inherit properties and methods from another class. It is used to create a hierarchy of classes that share a common structure and behavior.

class Person {
name: string;

constructor(name: string) {
this.name = name;
}

greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}

class Student extends Person {
constructor(name: string) {
super(name);
}

study() {
console.log(`${this.name} is studying.`);
}
}

let student = new Student("Bob");
student.greet(); // Outputs: Hello, my name is Bob.
student.study(); // Outputs: Bob is studying.

Polymorphism

Polymorphism allows methods to do different things based on the object it is acting upon, even though they share the same interface.

class Animal {
makeSound() {
console.log("Some sound");
}
}

class Cat extends Animal {
makeSound() {
console.log("Meow");
}
}

class Cow extends Animal {
makeSound() {
console.log("Moo");
}
}

function makeAnimalSound(animal: Animal) {
animal.makeSound();
}

let cat = new Cat();
let cow = new Cow();

makeAnimalSound(cat); // Outputs: Meow
makeAnimalSound(cow); // Outputs: Moo

Method Overriding

Method overriding allows a subclass to provide a specific implementation for a method that is already defined in its superclass.

class Vehicle {
startEngine() {
console.log("Starting engine...");
}
}

class Car extends Vehicle {
startEngine() {
console.log("Starting car engine...");
}
}

let car = new Car();
car.startEngine(); // Outputs: Starting car engine...

Comments

Recent Work

Free desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.

Learn More

BidBear

bidbear.io

Bidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.

Learn More