0
0
Typescriptprogramming~5 mins

Generic factory pattern in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the Generic Factory Pattern?
It is a design pattern that creates objects using a generic method or class, allowing you to produce different types of objects without specifying their exact classes upfront.
Click to reveal answer
beginner
How does a generic factory improve code reusability?
By using generics, the factory can create many types of objects with one method or class, reducing repeated code and making it easier to add new types later.
Click to reveal answer
intermediate
TypeScript syntax: How do you declare a generic factory function?
You use angle brackets with a type parameter, like <T>, before the function parameters. Example:
function createInstance<T>(c: new () => T): T { return new c(); }
Click to reveal answer
intermediate
What role does the 'new () => T' type play in a generic factory?
It tells TypeScript that the argument is a constructor function that can create an instance of type T without any parameters.
Click to reveal answer
beginner
Why use a generic factory instead of creating objects directly?
It separates object creation from usage, making code easier to maintain and extend. You can create new types without changing the factory logic.
Click to reveal answer
What does the generic type parameter <T> represent in a generic factory?
AThe type of object the factory will create
BThe name of the factory function
CA fixed class type
DThe return type of the factory function
In TypeScript, what does 'new () => T' mean in a factory function parameter?
AA variable of type T
BA function that returns a string
CA constructor that takes no arguments and returns type T
DA generic type constraint
Which benefit does a generic factory pattern provide?
ARemoves the need for classes
BMakes code slower
CRequires hardcoding all object types
DAllows creating multiple object types with one factory
What is a key advantage of separating object creation using a factory?
AEasier to change object creation without affecting usage
BObjects become immutable
CCode becomes more complex
DYou must write more code
How do you call a generic factory function to create an instance of class Car?
ACar.createInstance()
BcreateInstance<Car>(Car)
Cnew createInstance<Car>()
DcreateInstance()
Explain how a generic factory pattern works in TypeScript and why it is useful.
Think about how one function can create many types of objects.
You got /5 concepts.
    Describe the TypeScript syntax needed to define a generic factory function that creates instances of any class.
    Focus on the function signature and how it uses the constructor.
    You got /4 concepts.