CodeWithMihir

TypeScript Tutorial

TypeScript Classes Explained

Learn how classes work in TypeScript, including properties, methods, constructors, instances, and type checking with practical examples.

Welcome back! I am Mihir, and in this lesson we will learn classes in TypeScript.

Classes are templates for creating objects with shared properties and methods.


Basic Class

class User {
  name: string;

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

  greet() {
    return `Hello, ${this.name}`;
  }
}

Create an instance:

const user = new User("Mihir");

console.log(user.greet());

Class Properties Need Types

class Product {
  name: string;
  price: number;

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

TypeScript checks the values passed into the constructor.

const product = new Product("Keyboard", 2500);

Invalid:

const product = new Product("Keyboard", "expensive");

Methods

class Calculator {
  add(a: number, b: number): number {
    return a + b;
  }
}

const calculator = new Calculator();
console.log(calculator.add(10, 20));

Method parameters and return values can be typed like normal functions.


this Refers to the Instance

class Counter {
  count: number = 0;

  increment() {
    this.count += 1;
  }
}

this.count refers to the count property on the current object.


Property Initializers

You can give properties default values.

class Todo {
  completed: boolean = false;

  constructor(public title: string) {}
}

Every new Todo starts with completed as false.


Classes Create Types Too

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

function printUser(user: User) {
  console.log(user.name);
}

The class name can be used as a type.


Quick Recap

  • Classes create reusable object blueprints.
  • Properties and methods can be typed.
  • Constructors initialize new objects.
  • this refers to the current instance.
  • A class name can also be used as a type.

Next up, we will learn Constructors → in more detail.