blog podcast

Builder Pattern in Typescript

For anyone that has been around for a while with programming the refactoring problem that arises when you have classes with many properties that suddenly gets a new one is probably familiar. Suddenly you’ll have multiple unit tests spread around your code that needs a value for this new property that you have added. Many of these tests are probably unrelated to this new property, but you have to add something there anyway.

This is one of the problems that the builder pattern can help you with (another one being to have more verbose information on what values you are actually providing). This is one of the reasons that I’m a big fan of builders. I’m not a very big fan of writing a lot of code to create these builders though. In Java you have lombok that can generate builder classes for you. But what about Typescript? It turns out there is this really nice project called builder-pattern that comes to assist you. There are some slightly quirky things you have to think about, like adding the definite assignment assertion operator on your property (see documentation), but all in all it’s a great help to not have to write a lot of boiler plate code by hand.

Code of the Day

This is how it could look:

class Writer {
  s3Bucket!: string;
  mergeMode!: MergeMode;
  s3Client!: S3;

  constructor(s3Bucket: string, mergeMode: MergeMode, s3Client: S3) {
    this.s3Client = s3Client;
    this.s3Bucket = s3Bucket;
    this.mergeMode = mergeMode;
  }

  static builder(): IBuilder<Writer> {
    return Builder(Writer, new Writer('N/A', MergeMode.merge, new S3()));
  }