Sling Academy
Home/TypeScript/TypeScript & Class Constructor: A Complete Guide

TypeScript & Class Constructor: A Complete Guide

Last updated: January 07, 2024

Introduction

TypeScript enriches JavaScript with types and classes, offering an organized approach to web development that can significantly improve code maintainability and reusability. In this guide, we delve deep into the functionality of TypeScript class constructors, unveiling their potential to streamline object-oriented programming.

Understanding TypeScript Classes

TypeScript, as a superset of JavaScript, provides a structure for building objects using classes. Classes in TypeScript are blueprints for creating objects, providing a clear specification of what each object should contain in terms of data and behaviors. A class contains variables (properties) to define data and functions (methods) to define actions. Here is a simple example of a TypeScript class:

class Vehicle {
constructor(public make: string, public model: string) {
}

getInfo(): string {
return `This vehicle is a ${this.make} ${this.model}.`;
}
}

This class defines a Vehicle with a constructor that initializes the make and model of the vehicle. The getInfo() method can then use these properties.

Constructors in TypeScript

Constructors are special methods within a class responsible for initializing new objects. Whenever a new instance is created, the constructor is called, and it’s where you can set up your object. Here’s how a basic constructor looks in TypeScript:

class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
let myPet = new Animal('Simba');

The constructor here takes one parameter and assigns it to the object’s ‘name’ property.

Parameter Properties in TypeScript

TypeScript offers an even more concise way to declare and initialize class members right in the constructor known as parameter properties. With parameter properties, you can get rid of the declaration of the property and the manual assignment within the constructor body:

class Animal {
constructor(public name: string) {}
}

This constructor syntax is doing the same thing as before, but with less code. The ‘public’ access modifier before ‘name’ implies that ‘name’ should be treated both as a constructor parameter and a class property.

Advanced Constructor Patterns

As we progress into more complex cases, TypeScript constructors can also include logic to handle inheritance, method overriding, and much more. For instance, here’s how subclassing and constructor inheritance look:

class Bird extends Animal {
constructor(name: string, public canFly: boolean) {
super(name);
this.canFly = canFly;
}
}

In the Bird class, we first call the constructor of the base class (Animal) using ‘super’, and then proceed to specify unique properties for the Bird class.

Using Access Modifiers

TypeScript introduces several keywords as access modifiers – ‘public’, ‘private’, and ‘protected’. When used in constructors, these can control the visibility and accessibility of class members:

class Robot {
constructor(private id: number, protected type: string, public name: string) {
}
}
let terminator = new Robot(101, 'Assassin', 'T-800');

The ‘id’ can only be accessed within the Robot class, ‘type’ can be accessed by subclasses, and ‘name’ is public and can be accessed freely.

Default Parameters and Overloading

Default parameters can be provided in constructors to set default values. TypeScript also supports method overloading, including constructors:

class Point {
constructor(public x: number = 0, public y: number = 0) {}
}
class ColoredPoint extends Point {
constructor(x: number = 0, y: number = 0, public color: string = 'black') {
super(x, y);
}
}

In the ColoredPoint class, default values for x, y, and color are provided, increasing versatility with the ability to omit arguments upon instantiation.

Putting It All Together: A Practical Example

With all these concepts in hand, let’s create a practical example involving multiple classes and constructors:

class Person {
constructor(public name: string, public age: number) {}
}
class Employee extends Person {
constructor(name: string, age: number, private salary: number) {
super(name, age);
}
raiseSalary(amount: number): void {
this.salary += amount;
}
}

In this case, an Employee is a Person but with an additional salary property which can be modified using the raiseSalary method.

Conclusion

In conclusion, TypeScript’s typing system, coupled with class constructors, elevate JavaScript to a more robust level, one that simplifies the object creation process and adds a wealth of features beneficial for scalable projects. Understanding these concepts deepens your grasp on TypeScript and provides you the tools to craft more efficient, maintainable code.

Next Article: Class Public and Private Access Modifiers in TypeScript

Previous Article: ‘readonly’ Class Properties in TypeScript

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)