简体   繁体   中英

Enforce that the accepted Class type has a no arguments constructor

Given some function with a parameter for a Class (not an object or instance, but the Class itself), or equivalently a variable assigned to a Class.

The problem is to enforce that the Class assigned to the parameter is a Class that has a no argument constructor (only, as classes in JS may have at most one constructor from the spec, section 8.3 ( 8.3 )). The use case for this is to design a generic function that can construct (and return) instances of the given class.

Concretely, adding the required type checking for parameter c :

function acceptsAClassParameter(c) {
    return new c();
}

class MyClassWithNoArgsConstructor { constructor() { ... } }
class MyClassWithArgsConstructor { constructor(foo) { ... } }

acceptsAClassParameter(MyClassWithNoArgsConstructor);
acceptsAClassParameter(MyClassWithArgsConstructor); // type error

The TypeScript documentation for Generics provides an example of factories referring to class types by their constructor functions:

function create<Type>(c: { new (): Type }): Type {
  return new c();
}

The key is to use that, and avoid using a signature that would enforce that the constructor accepts no parameters, like: (...args: never[]) => any .

For the given example:

type NoArgsConstructor<T> = new () => T;
function createInstanceWithNoArgsConstructor<T>(c: NoArgsConstructor<T>) {
    return new c();
}

class MyClassWithNoArgsConstructor { constructor() { ... } }
class MyClassWithArgsConstructor { constructor(foo) { ... } }

createInstanceWithNoArgsConstructor(MyClassWithNoArgsConstructor);
createInstanceWithNoArgsConstructor(MyClassWithArgsConstructor); // Error: Types of construct signatures are incompatible.

TypeScript Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM