</>
Skip to content
TypeScript lessons (15/31)

TypeScript — Classes

Basic class

class Person {
    name: string;
    age: number;

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

    greet(): string {
        return `Hi, I'm ${this.name}!`;
    }
}

const alice = new Person("Alice", 30);
console.log(alice.greet());

Parameter properties

Shorthand for declaring and assigning constructor parameters:

class Person {
    constructor(
        public name: string,
        public age: number,
        private _id: string
    ) {}

    get id(): string {
        return this._id;
    }
}

const p = new Person("Alice", 30, "P001");
console.log(p.name); // Alice
// console.log(p._id); // Error: private

Access modifiers

class BankAccount {
    public owner: string;
    protected balance: number;
    private pin: string;

    constructor(owner: string, initial: number, pin: string) {
        this.owner = owner;
        this.balance = initial;
        this.pin = pin;
    }

    public deposit(amount: number): void {
        this.balance += amount;
    }

    public getBalance(): number {
        return this.balance;
    }

    protected validatePin(input: string): boolean {
        return input === this.pin;
    }
}

const acc = new BankAccount("Alice", 1000, "1234");
acc.deposit(500);
console.log(acc.getBalance()); // 1500
// console.log(acc.balance); // Error: protected
// console.log(acc.pin);     // Error: private

Inheritance

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

    speak(): string {
        return `${this.name} makes a sound`;
    }
}

class Dog extends Animal {
    speak(): string {
        return `${this.name} says Woof!`;
    }

    fetch(item: string): string {
        return `${this.name} fetches the ${item}`;
    }
}

const dog = new Dog("Rex");
console.log(dog.speak());     // Rex says Woof!
console.log(dog.fetch("ball")); // Rex fetches the ball

Abstract classes

abstract class Shape {
    abstract area(): number;
    abstract type: string;

    describe(): string {
        return `${this.type}: Area = ${this.area().toFixed(2)}`;
    }
}

class Circle extends Shape {
    type = "Circle";

    constructor(public radius: number) {
        super();
    }

    area(): number {
        return Math.PI * this.radius ** 2;
    }
}

class Rectangle extends Shape {
    type = "Rectangle";

    constructor(public width: number, public height: number) {
        super();
    }

    area(): number {
        return this.width * this.height;
    }
}

const shapes: Shape[] = [new Circle(5), new Rectangle(4, 6)];
shapes.forEach(s => console.log(s.describe()));

Static members

class MathHelper {
    static readonly PI = 3.14159;

    static circleArea(radius: number): number {
        return MathHelper.PI * radius ** 2;
    }

    static factorial(n: number): number {
        return n <= 1 ? 1 : n * MathHelper.factorial(n - 1);
    }
}

console.log(MathHelper.PI);              // 3.14159
console.log(MathHelper.circleArea(5));   // 78.5398
console.log(MathHelper.factorial(5));    // 120

Getters and setters

class Temperature {
    private _celsius: number;

    constructor(celsius: number) {
        this._celsius = celsius;
    }

    get fahrenheit(): number {
        return this._celsius * 9 / 5 + 32;
    }

    set fahrenheit(f: number) {
        this._celsius = (f - 32) * 5 / 9;
    }

    get celsius(): number {
        return this._celsius;
    }

    set celsius(c: number) {
        this._celsius = c;
    }
}

const temp = new Temperature(100);
console.log(temp.fahrenheit); // 212
temp.fahrenheit = 32;
console.log(temp.celsius);    // 0

Implements interface

interface Serializable {
    serialize(): string;
}

interface Loggable {
    log(): void;
}

class User implements Serializable, Loggable {
    constructor(public name: string, public age: number) {}

    serialize(): string {
        return JSON.stringify({ name: this.name, age: this.age });
    }

    log(): void {
        console.log(`User: ${this.name}, Age: ${this.age}`);
    }
}

Mini Practice

Write TypeScript code that:

  1. Creates a class with parameter properties
  2. Uses abstract classes for a shape hierarchy
  3. Implements an interface in a class
  4. Demonstrates getters and setters

Up Next

In the next lesson, you'll learn about Generics — writing reusable, type-safe code.

Related Topics

Frequently Asked Questions about Classes

What is Classes in TypeScript?

Classes is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Classes?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Classes.

Why is Classes important in TypeScript?

Classes is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.