0
0
Typescriptprogramming~10 mins

Generic factory 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 factory function that returns an instance of type T.

Typescript
function createInstance<T>(ctor: { new(): [1] }): T {
  return new ctor();
}
Drag options to blanks, or click blank then click option'
Aobject
Bvoid
Cany
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed type like 'object' instead of the generic type T.
Omitting the return type in the constructor signature.
2fill in blank
medium

Complete the code to define a generic factory interface with a create method.

Typescript
interface Factory<T> {
  create(): [1];
}
Drag options to blanks, or click blank then click option'
Avoid
Bany
CT
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using void as the return type which means no value is returned.
Using any which loses type safety.
3fill in blank
hard

Fix the error in the generic factory function signature to correctly accept a constructor.

Typescript
function factory<T>([1]: { new(): T }): T {
  return new ctor();
}
Drag options to blanks, or click blank then click option'
Actor
Bcreate
Cinstance
Dobj
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name different from the one used inside the function body.
Omitting the parameter name.
4fill in blank
hard

Fill both blanks to create a generic factory function that accepts a constructor and returns an instance.

Typescript
function create[1]<T>([2]: { new(): T }): T {
  return new ctor();
}
Drag options to blanks, or click blank then click option'
AInstance
BFactory
Cctor
Dobj
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent parameter names.
Using a function name that does not describe its purpose.
5fill in blank
hard

Fill all three blanks to implement a generic factory class with a create method.

Typescript
class Generic[1]<T> {
  constructor(private [2]: { new(): T }) {}
  create(): [3] {
    return new this.ctor();
  }
}
Drag options to blanks, or click blank then click option'
AFactory
Bctor
CT
DInstance
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect class or parameter names.
Not using the generic type T consistently.