public(default),private,protectedcontrol access.readonlyproperties can only be set in the constructor.- Parameter properties declare and assign in one step:
constructor(private name: string) implementschecks that a class matches an interface.
TypeScript Classes
Access modifiers, readonly and parameter properties.
✍️ 3 exercises + code challenge in this lessonKey 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
TypeScriptinterface 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());
12 25
TypeScript Classes Practice Exercises
Check what you learned in “TypeScript Classes”.
Make the property accessible only inside the class.
class Account { balance = 0; }
What does constructor(private name: string) do?
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().
Free sign-in required · Google login available
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