TypeScript Classes: How To Use Classes in TypeScript?

What are the classes in TypeScript?

TypeScript classes are a key part of object-oriented programming. It usually includes type annotations for its elements and, if needed, their parameters.

Here’s a basic example of how to define and use a class in TypeScript:

class Website {
    wbname: string;

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

    greeting() {
        console.log(`Hi, Welcome to ${this.wbname}`);
    }
}

let website = new Website("Itsourcecode");
website.greeting();  

Output:

Hi, Welcome to Itsourcecode

As you can see in our example above:

  • The website is the class name.
  • The wbname is a field (or property) of the class.
  • The constructors are special methods that get called when you create a new object from a class.
  • The greeting is a method of the class.

An instance of a class can be created by using the new keyword, followed by the class name and any arguments that need to be passed to the constructor.

In TypeScript, classes can serve as types. It simply means you can use the class name wherever TypeScript requires a type.
It’s important to note that TypeScript enhances JavaScript classes by adding types and visibility modifiers.

This means that the properties and methods of a class are typed using type annotations, much like how you would with variables.

Main Parts of TypeScript Classes

Members

These are the fields (properties) and methods in a TypeScript class. They can have types attached to them to specify what kind of values they can hold or return.

For example:

class Employee {
  name: string;
}
      
const employee = new Employee();
employee.name = "Itsourcecode";

console.log(employee);

Output:

Employee { name: 'Itsourcecode' }

Constructors

Constructors are special methods that get called when you create a new object from a class. Its main job is to set up the properties of the current instance.

In TypeScript, constructors help us set the starting state of an object. They can have parameters with types and default values.

For instance:

class Employee {
  // name and gender are private member variables
  public constructor(private name: string, private gender: string) {}

  public getName(): string {
    return this.name;
  }

  public getGender(): string {
    return this.gender;
  }
}

const employee = new Employee("Itsourcecode", "Male");
console.log(`Name: ${employee.getName()}`);
console.log(`Gender: ${employee.getGender()}`);

Output:

Name: Itsourcecode
Gender: Male

Visibility

TypeScript has public (default), private, and protected visibility for class members. This controls who can access these members in the code.

TypeScript has three main visibility settings:

  • public

This is the default setting and lets you access the class part from any place.

  • private

This setting only lets you access the class part from inside the class itself.

  • protected

This setting lets you access the class part from the class itself and any classes that come from it (which we’ll talk about in the inheritance below).

For example:

class Employee {
  private ename: string;

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

  public getName(): string {
    return this.ename;
  }
}
      
const employee = new Employee("Itsourecode");

console.log(employee.getName()); // The name attribute of the employee class can’t be accessed from outside the class because it’s marked as private.

Output:

Itsourcecode

Readonly

If a class field has readonly before it, you can’t change its value outside of the constructor.

For instance:

class Employee {
  // name, gender, and age are private readonly member variables
  public constructor(private readonly name: string, private readonly gender: string, private readonly age: number) {}

  public getName(): string {
    return this.name;
  }

  public getGender(): string {
    return this.gender;
  }
  
  public getAge(): number {
    return this.age;
  }
}

const employee = new Employee("Itsourcecode", "Male", 18);
console.log(`Name: ${employee.getName()}`);
console.log(`Gender: ${employee.getGender()}`);
console.log(`Age: ${employee.getAge()}`);

Output:

Name: Itsourcecode
Gender: Male
Age: 18

Inheritance

TypeScript classes can inherit from other classes using extends. This means a class can get properties and methods from another class.

For example:

// Define a base class
class Vehicle {
    constructor(public type: string) { }

    drive(distanceInKm: number = 0) {
        console.log(`The ${this.type} drove ${distanceInKm}km.`);
    }
}

// Define a class that extends the base class
class Car extends Vehicle {
    constructor(type: string) { super(type); }

    honk() {
        console.log('Beep! Beep!');
    }
}

const car = new Car('Sedan');
car.honk(); 
car.drive(50); 

Output:

Beep! Beep!
The Sedan drove 50km.

Please note that using “extends” Classes have the ability to inherit from one another using the “extends” keyword.

However, a class can only inherit from a single other class.

Interfaces

TypeScript classes can use implements to follow an interface. This makes sure the class follows a certain structure.

For example:

// Define an interface
interface Printable {
  print(): void;
}

// Define a class that implements the interface
class SampleDocument implements Printable {
  constructor(public website: string, public content: string) {}

  print(): void {
    console.log(`Website: ${this.website}`);
    console.log(`Content: ${this.content}`);
  }
}

// Create a new SampleDocument object
let doc = new SampleDocument('Itsourcecode', 'Itsourcecode.com is designed to help new and experienced programmers expand their knowledge and improve their programming skills!');

// Call the print method
doc.print(); 

Output:

Website: Itsourcecode
Content: Itsourcecode.com is designed to help new and experienced programmers expand their knowledge and improve their programming skills!

Abstract Classes

Abstract classes are basic classes that other classes can come from.

They can’t be made directly. Unlike an interface, an abstract class can have details about how its parts work.

The word “abstract” is used to make abstract classes and abstract methods in an abstract class.

For example:

abstract class Shape {
  public abstract getArea(): number;

  public toString(): string {
    return `Shape[area=${this.getArea()}]`;
  }
}

class Square extends Shape {
  public constructor(protected readonly side: number) {
    super();
  }

  public getArea(): number {
    return this.side * this.side;
  }
}

const square = new Square(5);
console.log(square.toString()); 

Output:

Shape[area=25]

Conclusion

So that’s the end of our discussion about TypeScript Classes. We’ve learned the different main parts of TypeScript classes.

Moreover, this article illustrates each concept with code examples and outputs, making it easier to understand.

For instance, it shows how to create an instance of a class, use classes as types, and add types and visibility modifiers to JavaScript classes.

I hope that this article helps you understand TypeScript classes.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment