Exploring TypeScript Classes: Structure, Properties, and Methods

Lesson Overview

Greetings! Today, we're revisiting TypeScript classes, the core building block of Object-Oriented Programming (OOP) in TypeScript. Through hands-on examples, we'll explore the fundamental concepts of TypeScript classes, including their structure, properties, and methods, while highlighting TypeScript's powerful type system.

TypeScript Classes Refresher

Let's begin with a refresher on TypeScript classes. Essential to OOP, TypeScript classes bundle relevant data and functions into compact units called objects. Consider a video game character, which is a typical example of a class instance, with specific properties (such as health or strength) and methods (such as attack or defense). TypeScript enhances this model by enabling static typing, which allows us to define types for properties and method parameters.

TypeScript
class GameCharacter {
    // constructor method with type annotations
    constructor(public name: string, public health: number, public strength: number) {}

    attack(otherCharacter: GameCharacter): void {    // method with parameter type and return type annotations
        otherCharacter.health -= this.strength;
    }
}

TypeScript classes facilitate the grouping of associated code elements, simplifying their management. Now, to better understand how the above example works, let's go through it step-by-step.

Structure of a TypeScript Class

A TypeScript class serves as a blueprint consisting of properties and methods, with type annotations adding clarity and robustness. While properties represent data relevant to a class instance, methods are actions or functions that manipulate this data. Each class includes a constructor function, which is used to define class properties with type annotations. The constructor initializes the properties when an object is created, and the public keyword automatically creates and assigns the properties to the class instance, eliminating the need for separate declarations. Without public, we would have to declare and assign properties separately inside the constructor.

An essential keyword within these methods is this, which represents the class instance. In object-oriented programming, it's needed to access the class's properties and methods. When a new class instance is created, TypeScript automatically passes it to the this parameter to access individual instance properties and methods using the this keyword. This mechanism allows each object to keep track of its own state and behaviors.

class GameCharacter {
    // constructor: defines class properties with type annotations
    constructor(public name: string, public health: number, public strength: number) {}
}

const character = new GameCharacter("Hero", 100, 20);  // object or instance of the class
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal