TS PlaygroundLearnJavaScriptClasses
javascript/intermediate

Classes

Use TypeScript classes with constructors, methods, and access modifiers.


Classes in TypeScript

TypeScript adds static typing to JavaScript's class syntax, making object-oriented code safer and more expressive.

Defining a class

class Animal {
  name: string;

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

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

const dog = new Animal('Rex');
console.log(dog.speak()); // "Rex makes a sound"

Access modifiers

  • public (default) — accessible anywhere
  • private — only inside the class body
  • protected — inside the class and subclasses
class BankAccount {
  private balance: number;

  constructor(initial: number) {
    this.balance = initial;
  }

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

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

Shorthand constructor params

TypeScript lets you declare and assign properties in one line:

class Point {
  constructor(public x: number, public y: number) {}
}
const p = new Point(3, 4);

Your task

Create a Rectangle class with:

  • width and height number properties set via the constructor
  • An area() method returning width * height
  • A perimeter() method returning 2 * (width + height)

Export the class as the default export.

// Create a Rectangle class with width, height, area(), and perimeter()
// Export it as the default export

No test results yet

Click Run Tests or press Ctrl+Enter

Type UtilitiesAsync / Await