Bird
Raised Fist0
Typescriptprogramming~20 mins

Generic factory pattern in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Factory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this generic factory function?

Consider the following TypeScript code using a generic factory pattern. What will be printed to the console?

Typescript
function createInstance<T>(ctor: new () => T): T {
  return new ctor();
}

class Dog {
  speak() { return "Woof!"; }
}

const dog = createInstance(Dog);
console.log(dog.speak());
A"Woof!"
Bundefined
CTypeError at runtime
DCompilation error
Attempts:
2 left
💡 Hint

The factory function creates an instance using the constructor passed in. What does dog.speak() return?

🧠 Conceptual
intermediate
1:30remaining
Which statement about generic factory pattern is true?

Choose the correct statement about the generic factory pattern in TypeScript.

AIt allows creating instances of any class type passed as a constructor parameter.
BIt requires the class to implement a specific interface with a factory method.
CIt can only create instances of classes without constructor parameters.
DIt cannot be used with classes that have private constructors.
Attempts:
2 left
💡 Hint

Think about how generics and constructors work in TypeScript.

🔧 Debug
advanced
2:00remaining
Why does this generic factory code cause a compilation error?

Examine the following TypeScript code. Why does it cause a compilation error?

Typescript
function createInstance<T>(ctor: new (name: string) => T, name: string): T {
  return new ctor();
}

class Cat {
  constructor(public name: string) {}
}

const cat = createInstance(Cat, "Whiskers");
AThe class Cat does not have a default constructor.
BThe generic type T is not specified explicitly.
CThe constructor is called without the required 'name' argument.
DThe function createInstance cannot accept parameters.
Attempts:
2 left
💡 Hint

Look at how the constructor is called inside the function.

📝 Syntax
advanced
2:00remaining
Which option correctly types a generic factory function for classes with parameters?

Choose the correct TypeScript signature for a generic factory function that can create instances of classes with any constructor parameters.

Afunction createInstance<T>(ctor: new (...args: T[]) => T): T
Bfunction createInstance<T>(ctor: new () => T, args: any[]): T
Cfunction createInstance<T>(ctor: T, ...args: any[]): T
Dfunction createInstance<T>(ctor: new (...args: any[]) => T, ...args: any[]): T
Attempts:
2 left
💡 Hint

Consider how to type a constructor with any number of parameters.

🚀 Application
expert
2:30remaining
How many items are in the resulting map after using this generic factory?

Given the following TypeScript code using a generic factory to create multiple instances, how many entries does the instances map contain?

Typescript
class User {
  constructor(public id: number) {}
}

class Product {
  constructor(public id: number) {}
}

function createInstance<T>(ctor: new (id: number) => T, id: number): T {
  return new ctor(id);
}

const instances = new Map<string, unknown>();
instances.set("user1", createInstance(User, 1));
instances.set("user2", createInstance(User, 2));
instances.set("product1", createInstance(Product, 1));
instances.set("user1", createInstance(User, 3));
A1
B3
C2
D4
Attempts:
2 left
💡 Hint

Remember how Map keys work when adding entries with the same key.

Practice

(1/5)
1.

What is the main purpose of the Generic factory pattern in TypeScript?

easy
A. To enforce strict typing on all variables.
B. To create objects without specifying their exact class.
C. To handle asynchronous operations automatically.
D. To optimize code for faster execution.

Solution

  1. Step 1: Understand the pattern's goal

    The generic factory pattern is designed to create objects without needing to know their exact class ahead of time.
  2. Step 2: Compare options with the pattern's purpose

    To create objects without specifying their exact class. correctly states this purpose. Other options describe unrelated features.
  3. Final Answer:

    To create objects without specifying their exact class. -> Option B
  4. Quick Check:

    Generic factory pattern = create objects flexibly [OK]
Hint: Focus on object creation without class details [OK]
Common Mistakes:
  • Confusing with async handling
  • Thinking it enforces variable typing
  • Assuming it optimizes runtime speed
2.

Which of the following is the correct syntax to declare a generic factory function in TypeScript?

function create<T>(): T { /* ... */ }
easy
A. function create<T>(): T { return new T(); }
B. function create<T>(): T { return T(); }
C. function create<T>(): T { return new Object(); }
D. function create<T>(): T { return {} as T; }

Solution

  1. Step 1: Analyze generic function syntax

    The function declares a generic type T and returns an object of type T.
  2. Step 2: Check return statements for correctness

    function create<T>(): T { return {} as T; } uses a type assertion {} as T which is valid to create a generic placeholder object. function create<T>(): T { return new T(); } tries to use new T() which is invalid because T is a type parameter, not a constructor. function create<T>(): T { return T(); } calls T() like a function which is invalid. function create<T>(): T { return new Object(); } returns a generic object but not typed as T.
  3. Final Answer:

    function create<T>(): T { return {} as T; } -> Option D
  4. Quick Check:

    Generic factory syntax = use type assertion [OK]
Hint: Use type assertion to return generic type instance [OK]
Common Mistakes:
  • Trying to instantiate generic type with new
  • Calling generic type as a function
  • Returning untyped objects without assertion
3.

What will be the output of this TypeScript code using a generic factory pattern?

interface Animal { speak(): string; }
class Dog implements Animal { speak() { return "Woof"; } }
function createAnimal<T extends Animal>(ctor: new () => T): T {
  return new ctor();
}
const dog = createAnimal(Dog);
console.log(dog.speak());
medium
A. "Woof"
B. undefined
C. TypeError at runtime
D. Compilation error

Solution

  1. Step 1: Understand the factory function behavior

    The function createAnimal takes a constructor ctor and returns a new instance of type T which extends Animal.
  2. Step 2: Trace the code execution

    We pass Dog class to createAnimal, so it returns a new Dog instance. Calling dog.speak() returns "Woof".
  3. Final Answer:

    "Woof" -> Option A
  4. Quick Check:

    Generic factory creates Dog, speak() = "Woof" [OK]
Hint: Trace constructor call and method output [OK]
Common Mistakes:
  • Assuming generic type can't be instantiated
  • Confusing type constraints with runtime errors
  • Expecting undefined instead of method return
4.

Identify the error in this generic factory function and select the fix.

function createInstance<T>(): T {
  return new T();
}
medium
A. Add a constructor parameter: ctor: new () => T and return new ctor().
B. Remove new keyword and call T() directly.
C. Change return type to any to avoid errors.
D. Use Object.create(T) instead of new T().

Solution

  1. Step 1: Identify why new T() causes error

    TypeScript does not allow new T() because T is a type parameter, not a constructor function.
  2. Step 2: Apply correct fix using constructor parameter

    Passing a constructor function ctor: new () => T allows calling new ctor() to create an instance of T.
  3. Final Answer:

    Add a constructor parameter: ctor: new () => T and return new ctor(). -> Option A
  4. Quick Check:

    Generic factory needs constructor parameter [OK]
Hint: Pass constructor as parameter to instantiate generic type [OK]
Common Mistakes:
  • Trying to instantiate generic type directly
  • Removing new keyword incorrectly
  • Changing return type to any loses type safety
5.

You want to create a generic factory that can produce different shapes with a draw() method. Which approach correctly uses the generic factory pattern to support adding new shapes easily?

interface Shape { draw(): void; }
class Circle implements Shape { draw() { console.log("Circle"); } }
class Square implements Shape { draw() { console.log("Square"); } }
// What is the best factory implementation?
hard
A. function createShape<T>(): T { return {} as T; }
B. function createShape(): Shape { return new Circle(); }
C. function createShape(ctor: new () => T): T { return new ctor(); }
D. function createShape(type: string): Shape { if(type === 'circle') return new Circle(); else return new Square(); }

Solution

  1. Step 1: Understand the requirement for flexibility

    The factory should create any shape implementing Shape without hardcoding types.
  2. Step 2: Evaluate each option

    function createShape(ctor: new () => T): T { return new ctor(); } uses a generic constructor parameter allowing easy addition of new shapes. function createShape(): Shape { return new Circle(); } always returns Circle, no flexibility. function createShape(type: string): Shape { if(type === 'circle') return new Circle(); else return new Square(); } uses string checks, less type-safe and harder to extend. function createShape<T>(): T { return {} as T; } returns an empty object cast to T, which is unsafe.
  3. Final Answer:

    function createShape<T extends Shape>(ctor: new () => T): T { return new ctor(); } -> Option C
  4. Quick Check:

    Generic factory with constructor param = flexible shape creation [OK]
Hint: Use generic constructor param for flexible object creation [OK]
Common Mistakes:
  • Hardcoding return types limits extensibility
  • Using string type checks reduces type safety
  • Casting empty objects loses real behavior
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