Consider the following TypeScript code using a generic factory pattern. What will be printed to the console?
function createInstance<T>(ctor: new () => T): T { return new ctor(); } class Dog { speak() { return "Woof!"; } } const dog = createInstance(Dog); console.log(dog.speak());
The factory function creates an instance using the constructor passed in. What does dog.speak() return?
The createInstance function takes a class constructor and returns a new instance. Since Dog has a speak method returning "Woof!", the console prints "Woof!".
Choose the correct statement about the generic factory pattern in TypeScript.
Think about how generics and constructors work in TypeScript.
The generic factory pattern uses a constructor signature new () => T to create instances of any class type passed in. It does not require interfaces or factory methods, but it does require a constructor without parameters.
Examine the following TypeScript code. Why does it cause a compilation error?
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");
Look at how the constructor is called inside the function.
The constructor signature requires a string argument, but new ctor() is called without arguments, causing a compilation error.
Choose the correct TypeScript signature for a generic factory function that can create instances of classes with any constructor parameters.
Consider how to type a constructor with any number of parameters.
Option D correctly uses a constructor signature with rest parameters new (...args: any[]) => T and passes the arguments to create instances with any constructor parameters.
Given the following TypeScript code using a generic factory to create multiple instances, how many entries does the instances map contain?
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));
Remember how Map keys work when adding entries with the same key.
The key "user1" is used twice. The second set call overwrites the first. So the map has keys: "user1", "user2", "product1" → 3 entries.