0
0
Typescriptprogramming~30 mins

Generic factory pattern in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic Factory Pattern in TypeScript
📖 Scenario: You are building a simple system that creates different types of vehicles. Each vehicle has a name and a method to describe itself. You want to use a generic factory pattern to create vehicles easily without repeating code.
🎯 Goal: Build a generic factory function in TypeScript that can create different vehicle objects with a common interface. You will create vehicle classes, a factory function, and use it to create and display vehicle details.
📋 What You'll Learn
Create two vehicle classes: Car and Bike, each with a name property and a describe() method.
Create a generic factory function called createVehicle that takes a class constructor and a name, then returns an instance of that class.
Use the factory function to create a Car named "Sedan" and a Bike named "Mountain Bike".
Call the describe() method on both created vehicles and print the results.
💡 Why This Matters
🌍 Real World
Generic factory patterns help create objects flexibly in software like games, simulations, or business apps where many similar objects are needed.
💼 Career
Understanding generic factories is useful for software developers to write reusable and scalable code, especially in TypeScript and other typed languages.
Progress0 / 4 steps
1
Create Vehicle Classes
Create two classes called Car and Bike. Each class should have a constructor that takes a name string and stores it in a public property called name. Also, add a method called describe() that returns a string: for Car return `This is a car named ${this.name}`, and for Bike return `This is a bike named ${this.name}`.
Typescript
Need a hint?

Use class keyword to create classes. The constructor should take name and assign it to a public property. The describe() method returns a string describing the vehicle.

2
Create Generic Factory Function
Create a generic function called createVehicle that takes two parameters: a class constructor ctor of type new (name: string) => T and a name string. The function should return a new instance of T by calling new ctor(name).
Typescript
Need a hint?

Use a generic function with a constructor type parameter. The function creates and returns a new instance using new ctor(name).

3
Use Factory to Create Vehicles
Use the createVehicle function to create a Car instance named "Sedan" and a Bike instance named "Mountain Bike". Store them in variables called myCar and myBike respectively.
Typescript
Need a hint?

Call createVehicle with the class and name to create instances. Assign them to myCar and myBike.

4
Print Vehicle Descriptions
Use console.log to print the result of calling describe() on myCar and myBike.
Typescript
Need a hint?

Use console.log(myCar.describe()) and console.log(myBike.describe()) to print the descriptions.