How do you define a class in TypeScript?

Beginner

Answer

Classes in TypeScript include type annotations and access modifiers:

class Person {
  // Properties
  private _id: number;
  protected name: string;
  public email: string;

  constructor(id: number, name: string, email: string) {
    this._id = id;
    this.name = name;
    this.email = email;
  }

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

  protected getId(): number {
    return this._id;
  }
}