#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 21 of 48medium

How do Classes work in TypeScript?

Class syntax with types.

What You'll Learn

  • Class with types
  • Access modifiers
  • Abstract classes

Basic Class

code.tsTypeScript
class User {
  name: string;
  age: number;

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

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

const user = new User("John", 30);

Access Modifiers

code.tsTypeScript
class BankAccount {
  public owner: string;      // accessible everywhere
  private balance: number;   // only in this class
  protected id: string;      // this class and subclasses

  constructor(owner: string, balance: number) {
    this.owner = owner;
    this.balance = balance;
    this.id = crypto.randomUUID();
  }
}

Shorthand Constructor

code.tsTypeScript
class User {
  constructor(
    public name: string,
    private age: number,
    readonly id: string
  ) {}
}
// Automatically creates and assigns properties

Abstract Classes

code.tsTypeScript
abstract class Shape {
  abstract getArea(): number;

  describe(): string {
    return `Area: ${this.getArea()}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

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