0
0
Typescriptprogramming~30 mins

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

Choose your learning style9 modes available
Generic Repository Pattern in TypeScript
📖 Scenario: You are building a simple data management system for different types of items like books and movies. To keep your code clean and reusable, you want to create a generic repository that can handle basic operations for any type of item.
🎯 Goal: Build a generic repository class in TypeScript that can store, add, and retrieve items of any type. Then use it to manage a collection of books.
📋 What You'll Learn
Create a generic repository class with methods to add and get all items
Use a generic type parameter to allow storing any type of item
Create a Book interface with title and author properties
Create an instance of the repository for books and add some books
Print the list of books stored in the repository
💡 Why This Matters
🌍 Real World
Generic repositories are used in software to manage data storage and retrieval in a consistent way, no matter what kind of data you have.
💼 Career
Understanding generic patterns and TypeScript generics is important for writing scalable and maintainable code in many professional web development jobs.
Progress0 / 4 steps
1
Create the Book interface
Create an interface called Book with two string properties: title and author.
Typescript
Need a hint?

Use the interface keyword to define the shape of a book object.

2
Create the generic Repository class
Create a generic class called Repository with a type parameter T. Inside, create a private array called items to store objects of type T. Initialize it as an empty array.
Typescript
Need a hint?

Use class Repository<T> and declare private items: T[] = []; inside it.

3
Add add and getAll methods to Repository
Inside the Repository class, add a method called add that takes a parameter item of type T and adds it to the items array. Also add a method called getAll that returns the array of items.
Typescript
Need a hint?

Define add(item: T): void to push item into items. Define getAll(): T[] to return items.

4
Use Repository with Book and print all books
Create a variable called bookRepo as a new Repository<Book>. Add two books to bookRepo using the add method with these exact values: { title: "1984", author: "George Orwell" } and { title: "The Hobbit", author: "J.R.R. Tolkien" }. Then print the result of bookRepo.getAll() using console.log.
Typescript
Need a hint?

Create bookRepo as new Repository<Book>(). Use add twice with the exact book objects. Print with console.log(bookRepo.getAll()).