TypeScript Classes with Types
TypeScript adds type annotations to classes, making class-based code safer and more maintainable.
Class Property Types
Annotate properties to ensure values always match the expected type:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let person = new Person("John", 25);
person.age = 30; // OK
person.age = "old"; // Error
Access Modifiers
public (default), private, and protected control visibility:
class BankAccount {
private balance: number;
protected accountNumber: string;
public owner: string;
constructor(owner: string, balance: number, accountNumber: string) {
this.owner = owner;
this.balance = balance;
this.accountNumber = accountNumber;
}
deposit(amount: number): void {
if (amount > 0) this.balance += amount;
}
}
Constructor Shorthand
public, private, or protected before a parameter creates and initializes the property automatically:
class User {
constructor(
public name: string,
public age: number,
private email: string
) {}
}
let user = new User("John", 25, "[email protected]");
console.log(user.name); // "John"
Implementing Interfaces
Classes can implement interfaces to enforce a contract:
interface Shape {
color: string;
getArea(): number;
}
class Circle implements Shape {
color: string;
radius: number;
constructor(radius: number, color: string) {
this.color = color;
this.radius = radius;
}
getArea(): number {
return Math.PI * this.radius ** 2;
}
}
Remember: readonly properties cannot change after initialization.
Best Practices
- Always type class properties to prevent
anyinference - Use
implementsto enforce class contracts with interfaces - Use constructor shorthand for simple property assignments
- Use
private/protectedfor encapsulation - Use
readonlyfor immutable properties
Common Mistakes
- Missing property types defaults to
any - Not implementing interfaces means no enforced shape
- Using
anyin constructors defeats type safety - Forgetting access modifiers makes everything public