Building Immutable Orders with Typescript

Ole Ersoy
Ole Ersoy
Apr 23 · 2 min read
Photo by SpaceX on Unsplash

Scenario

“Id like one SpaceX Rocket Please. I need it to be fire engine red and gold though”.

We wish to create order instances for SKU sku123 and with price $10 . The only thing that will vary for each order is the quantity. The Order class has these properties.

export class Order {
public readonly sku;
public readonly quantity;
public readonly price;
public readonly total;
}
}

The orders will be built like this:

let builder = new OrderBuilder(10, 'sku123');const order = builder.setQuantity(10).build();const order2 = builder.setQuantity(20).build();console.log(order1);console.log(order2);

Approach

The full implementation for our immutable Typescript class and the corresponding builder look like this:

With that implementation we can build two orders with quantities 10 and 20 like this:

let builder = new OrderBuilder('sku123', 10);const order1 = builder.setQuantity(10).build();const order2 = builder.setQuantity(20).build();console.log(order1);console.log(order2);

Demo

Flexibility

Since our builders sku and price properties are readonly we are passing these in via the builders constructor. This means we can not change these properties post builder construction, thus the design is a bit rigid.

If we want to change these properties on the fly we can remove the readonly markers and implement builder setters for sku and price . We can now change these properties on the fly as well, giving us more flexibility. Here is a demo:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade