0
0
Typescriptprogramming~10 mins

Generic repository pattern in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AT
Bnumber
Cvoid
Dstring
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.
2fill in blank
medium

Complete 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'
Aany
Bobject
CT
Dunknown
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.
3fill in blank
hard

Fix 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'
AT
BU
CItem
DK
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different generic type parameter name than the interface.
Omitting the generic parameter in the class declaration.
4fill in blank
hard

Fill 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'
AT
BT[]
Cany
Dvoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using any instead of the generic type T.
Returning void instead of an array.
5fill in blank
hard

Fill 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'
Achanges
BT
Dupdates
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the changes parameter and spread variable.
Not using Partial type for changes.