TypeScript Classes

Access modifiers, readonly and parameter properties.

✍️ 3 exercises + code challenge in this lesson
  • public (default), private, protected control access.
  • readonly properties can only be set in the constructor.
  • Parameter properties declare and assign in one step: constructor(private name: string)
  • implements checks that a class matches an interface.

Key Takeaways: TypeScript Classes

Mastering TypeScript Classes helps you write clean and reliable TypeScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

TypeScript Classes Code Example

TypeScript
interface Shape {
  area(): number;
}

class Rectangle implements Shape {
  constructor(private readonly w: number, private readonly h: number) {}

  area(): number {
    return this.w * this.h;
  }
}

class Square extends Rectangle {
  constructor(side: number) {
    super(side, side);
  }
}

console.log(new Rectangle(3, 4).area(), new Square(5).area());
Output
12 25
Free sign-in required · Google login available

TypeScript Classes Practice Exercises

Check what you learned in “TypeScript Classes”.

/ 3 solved
Fill in the blank

Make the property accessible only inside the class.

class Account {  balance = 0; }
✓ Correct! Not quite. Try again.
Multiple choice

What does constructor(private name: string) do?

✓ Correct! Not quite. Try again.
Code challenge

Create class Counter with a private count = 0, a method inc() that adds 1, and a method value() returning count. Call inc() twice and log value().

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services