Complete the code to declare a generic repository interface.
interface IRepository<T> {
getById(id: number): [1];
}The method getById returns an object of the generic type T.
Complete the code to define a generic method to add an item to the repository.
interface IRepository<T> {
add(item: [1]): void;
}The add method accepts an item of the generic type T.
Fix the error in the generic repository class declaration.
class Repository<[1]> implements IRepository<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } getById(id: number): T | undefined { return this.items.find(item => (item as any).id === id); } }
The class must declare the generic type parameter T to match the interface.
Fill both blanks to create a generic repository method that returns all items matching a condition.
class Repository<T> implements IRepository<T> { private items: T[] = []; findAll(predicate: (item: [1]) => boolean): [2] { return this.items.filter(predicate); } }
T.The predicate function takes an item of type T, and the method returns an array of T.
Fill all three blanks to implement a generic repository method that updates an item by id.
class Repository<T extends { id: number }> implements IRepository<T> { private items: T[] = []; update(id: number, [1]: Partial<[2]>): boolean { const index = this.items.findIndex(item => item.id === id); if (index === -1) return false; this.items[index] = { ...this.items[index], ...[3] }; return true; } }
The method takes changes of type Partial<T> and merges them into the existing item.
