0
0
Typescriptprogramming~30 mins

Builder pattern with generics in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Builder pattern with generics
📖 Scenario: You are creating a system to build different types of vehicles. Each vehicle has some common parts like wheels and color, but also some unique parts. You want to use a builder pattern with generics to create vehicles flexibly.
🎯 Goal: Build a generic VehicleBuilder class that can build vehicles with different specific parts. Then create a Car type and use the builder to create a car object.
📋 What You'll Learn
Create a generic VehicleBuilder<T> class with methods to set wheels and color.
Add a method setPart(key: keyof T, value: T[keyof T]) to set specific parts.
Add a build() method that returns the complete vehicle object combining common and specific parts.
Create a Car interface with engine and doors properties.
Use VehicleBuilder<Car> to build a car with 4 wheels, color 'red', engine 'V8', and 4 doors.
Print the final car object.
💡 Why This Matters
🌍 Real World
Builder patterns with generics help create flexible and reusable code for building complex objects like vehicles, UI components, or configurations.
💼 Career
Understanding builder patterns and generics is useful for software developers working on scalable TypeScript applications, improving code maintainability and readability.
Progress0 / 4 steps
1
Create the generic VehicleBuilder class
Create a generic class called VehicleBuilder<T> with a private property vehicle initialized as an empty object of type T & { wheels?: number; color?: string }.
Typescript
Need a hint?

Use class VehicleBuilder<T> and initialize vehicle as an empty object with type T & { wheels?: number; color?: string }.

2
Add methods to set wheels, color, and specific parts
Add three methods inside VehicleBuilder<T>: setWheels(wheels: number): this, setColor(color: string): this, and setPart(key: keyof T, value: T[keyof T]): this. Each method should set the corresponding property on this.vehicle and return this.
Typescript
Need a hint?

Each method sets a property on this.vehicle and returns this to allow chaining.

3
Add the build method and create Car interface
Add a method build(): T & { wheels?: number; color?: string } that returns this.vehicle. Then create an interface Car with properties engine: string and doors: number.
Typescript
Need a hint?

The build method returns the complete vehicle object. The Car interface defines specific parts.

4
Use VehicleBuilder to build a Car and print it
Create a variable carBuilder as new VehicleBuilder<Car>(). Use method chaining to set wheels to 4, color to 'red', engine to 'V8', and doors to 4. Then create a variable car by calling carBuilder.build(). Finally, print car using console.log(car).
Typescript
Need a hint?

Use method chaining on carBuilder to set all properties, then call build() and print the result.