Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a generic repository interface.
Typescript
interface IRepository<T> {
getById(id: number): [1];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a fixed type like number or string instead of the generic type.
Using void as return type which means no value is returned.
✗ Incorrect
The method getById returns an object of the generic type T.
2fill in blank
mediumComplete the code to define a generic method to add an item to the repository.
Typescript
interface IRepository<T> {
add(item: [1]): void;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-generic type like any or object which loses type safety.
Using unknown which requires type assertions.
✗ Incorrect
The add method accepts an item of the generic type T.
3fill in blank
hardFix the error in the generic repository class declaration.
Typescript
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); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different generic type parameter name than the interface.
Omitting the generic parameter in the class declaration.
✗ Incorrect
The class must declare the generic type parameter T to match the interface.
4fill in blank
hardFill both blanks to create a generic repository method that returns all items matching a condition.
Typescript
class Repository<T> implements IRepository<T> { private items: T[] = []; findAll(predicate: (item: [1]) => boolean): [2] { return this.items.filter(predicate); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using any instead of the generic type
T.Returning void instead of an array.
✗ Incorrect
The predicate function takes an item of type T, and the method returns an array of T.
5fill in blank
hardFill all three blanks to implement a generic repository method that updates an item by id.
Typescript
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; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the changes parameter and spread variable.
Not using Partial type for changes.
✗ Incorrect
The method takes changes of type Partial<T> and merges them into the existing item.