RecipesChapter 11: Classes

Working with Strict Property Initialization

Recipe 11.7 from The TypeScript Cookbook

class Account {
  userName!: string;
  state: State = "active";
  orders?: number[];

  constructor(public id: number) {
    fetch(`/api/getName?id=${id}`)
      .then((res) => res.json())
      .then((data: User) => (this.userName = data.userName));
  }
}
Open in TypeScript Playground →