Bird
Raised Fist0
Typescriptprogramming~5 mins

Generic repository pattern in Typescript - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is the Generic Repository Pattern?
It is a design pattern that provides a generic way to handle data operations like create, read, update, and delete (CRUD) for different types of data entities using a single reusable interface.
Click to reveal answer
beginner
Why use a Generic Repository Pattern in TypeScript?
It helps avoid repeating the same data access code for different entities by using TypeScript generics, making the code cleaner, easier to maintain, and type-safe.
Click to reveal answer
intermediate
What TypeScript feature is essential for implementing a Generic Repository?
TypeScript generics allow the repository to work with any data type while keeping type safety, so you can write one repository interface and class that works with many entity types.
Click to reveal answer
intermediate
Example method signature for fetching an entity by ID in a generic repository?
fetchById(id: string): Promise<T | null> - where T is the generic type representing the entity.
Click to reveal answer
intermediate
How does the Generic Repository Pattern improve testing?
It allows you to mock or replace the repository easily in tests because the interface is generic and consistent, making unit tests simpler and more reliable.
Click to reveal answer
What does the Generic Repository Pattern primarily help with?
AManaging user authentication
BReusing data access code for multiple entity types
CImproving UI design
DOptimizing network requests
In TypeScript, what feature allows a repository to handle different data types safely?
AGenerics
BEnums
CInterfaces
DDecorators
Which method would you expect in a generic repository interface?
Asave(entity: T): Promise<T>
BrenderUI(): void
CconnectToServer(): boolean
DcalculateSum(a: number, b: number): number
What is a benefit of using the Generic Repository Pattern for testing?
AImproved CSS styling
BFaster UI rendering
CEasier to mock data access
DAutomatic database backups
Which of these is NOT a typical CRUD operation in a repository?
ACreate
BUpdate
CDelete
DCompile
Explain the Generic Repository Pattern and why it is useful in TypeScript projects.
Think about how one interface can work for many data types.
You got /4 concepts.
    Describe how you would implement a method to fetch an entity by ID in a generic repository interface.
    Focus on the input parameter and the return type.
    You got /3 concepts.

      Practice

      (1/5)
      1.

      What is the main benefit of using the Generic Repository Pattern in TypeScript?

      easy
      A. It allows handling multiple data types with one reusable class.
      B. It automatically generates UI components.
      C. It replaces the need for TypeScript interfaces.
      D. It compiles TypeScript code faster.

      Solution

      1. Step 1: Understand the purpose of the generic repository

        The generic repository pattern is designed to handle data operations for many types using one class or interface.
      2. Step 2: Compare options with the pattern's purpose

        Only It allows handling multiple data types with one reusable class. correctly describes this benefit. Options A, B, and C are unrelated to the pattern's main use.
      3. Final Answer:

        It allows handling multiple data types with one reusable class. -> Option A
      4. Quick Check:

        Generic repository = reusable data handler [OK]
      Hint: Generic means reusable for many types [OK]
      Common Mistakes:
      • Thinking it generates UI components
      • Confusing it with TypeScript compilation
      • Believing it removes interfaces
      2.

      Which of the following is the correct way to declare a generic repository interface in TypeScript?

      interface IRepository<T> {
        add(item: T): void;
        get(id: number): T | undefined;
      }
      easy
      A. interface IRepository<T> { add(item: T): void; get(id: number): T | undefined; }
      B. interface IRepository { add(item: any): void; get(id: number): any; }
      C. interface IRepository<T> { add(item: any): void; get(id: number): T; }
      D. interface IRepository<T> { add(item: T): T; get(id: string): T | undefined; }

      Solution

      1. Step 1: Check generic syntax correctness

        interface IRepository<T> { add(item: T): void; get(id: number): T | undefined; } correctly declares a generic interface with type parameter <T> and uses it consistently in method signatures.
      2. Step 2: Validate method signatures

        interface IRepository<T> { add(item: T): void; get(id: number): T | undefined; }'s methods use item: T and return T | undefined for get, which is correct. Other options misuse types or parameter types.
      3. Final Answer:

        interface IRepository<T> { add(item: T): void; get(id: number): T | undefined; } -> Option A
      4. Quick Check:

        Generic interface syntax = interface IRepository<T> { add(item: T): void; get(id: number): T | undefined; } [OK]
      Hint: Generic interfaces use <T> and consistent types [OK]
      Common Mistakes:
      • Using 'any' instead of generic type T
      • Mismatching parameter and return types
      • Using wrong id parameter type
      3.

      Given the following generic repository class, what will be the output of the console.log statement?

      class Repository<T> {
        private items: T[] = [];
        add(item: T): void {
          this.items.push(item);
        }
        getAll(): T[] {
          return this.items;
        }
      }
      
      const repo = new Repository<string>();
      repo.add('apple');
      repo.add('banana');
      console.log(repo.getAll());
      medium
      A. Error: Type mismatch
      B. ['apple']
      C. []
      D. ['apple', 'banana']

      Solution

      1. Step 1: Understand the generic repository usage

        The repository is created for strings, so it stores string items in an array.
      2. Step 2: Trace the add and getAll methods

        Two strings 'apple' and 'banana' are added, so getAll returns ['apple', 'banana'].
      3. Final Answer:

        ['apple', 'banana'] -> Option D
      4. Quick Check:

        Added items = ['apple', 'banana'] [OK]
      Hint: Add items then getAll returns all added [OK]
      Common Mistakes:
      • Expecting only one item in output
      • Thinking getAll returns empty array
      • Confusing type errors
      4.

      Identify the error in this generic repository implementation:

      class Repository<T> {
        private items: T[] = [];
        add(item: T): void {
          this.items.push(item);
        }
        get(id: number): T {
          return this.items[id];
        }
      }
      
      const repo = new Repository<number>();
      console.log(repo.get(0));
      medium
      A. The items array should be public, not private.
      B. The add method should return the added item.
      C. The get method should return T | undefined to handle missing items.
      D. The generic type T cannot be used with arrays.

      Solution

      1. Step 1: Analyze the get method return type

        The get method returns this.items[id], which may be undefined if the index is invalid.
      2. Step 2: Check return type compatibility

        Since undefined is possible, the return type should be T | undefined to avoid runtime errors.
      3. Final Answer:

        The get method should return T | undefined to handle missing items. -> Option C
      4. Quick Check:

        Return type must allow undefined for missing index [OK]
      Hint: Allow undefined return for invalid index [OK]
      Common Mistakes:
      • Ignoring possible undefined return
      • Changing add method unnecessarily
      • Making items public without reason
      5.

      You want to create a generic repository that supports updating an item by id. Which method signature correctly fits this requirement?

      hard
      A. update(item: T): void
      B. update(id: number, item: T): boolean
      C. update(id: string, item: any): T
      D. update(id: number): T | undefined

      Solution

      1. Step 1: Understand update method needs

        To update an item, you need to specify which item by id and provide the new item data.
      2. Step 2: Evaluate method signatures

        update(id: number, item: T): boolean takes an id and a new item of type T, returning boolean to indicate success, which fits the requirement best.
      3. Final Answer:

        update(id: number, item: T): boolean -> Option B
      4. Quick Check:

        Update needs id and new item, returns success [OK]
      Hint: Update needs id and new item, returns success boolean [OK]
      Common Mistakes:
      • Missing id parameter
      • Using wrong parameter types
      • Returning wrong type from update
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard