Design Patterns - Static Factory Method Pattern in TypeScript

Before you look at the Static Factory Method pattern example in TypeScript, you can see my post about what is the Static Factory Method pattern.

Example of the static factory method in TypeScript

class User {
  private firstName: string;
  private lastName: string;
  private email: string;

  get getFirstName(): string {
    return this.firstName;
  }
  get getLastName(): string {
    return this.lastName;
  }
  get getEmail(): string {
    return this.email;
  }

  private constructor(firstName: string, lastName: string, email: string) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
  }

  static create(firstName: string, lastName: string, email: string): User {
    return new User(firstName, lastName, email);
  }
}

About this code snippet:

  • The constructor is private.
  • To create new instances of the user class, just use the static factory method with: User.create("John", "Doe", "john@doe.com").