When working with a function that takes a parameter representing a Class (not an object or instance, but the Class itself), or essentially a variable assigned to a Class.
The challenge is ensuring that the Class assigned to the parameter has a constructor with no arguments (only, as JS classes can have at most one constructor based on the spec, section 8.3 (8.3)). This is useful for creating a generic function that can instantiate (and return) objects of the specified class.
To implement the necessary type checking for parameter c
:
function acceptsAClassParameter(c) {
return new c();
}
class MyClassWithNoArgsConstructor { constructor() { ... } }
class MyClassWithArgsConstructor { constructor(foo) { ... } }
acceptsAClassParameter(MyClassWithNoArgsConstructor);
acceptsAClassParameter(MyClassWithArgsConstructor); // results in a type error