Home > Software design >  Type-safe class construction within generic class in TYPESCRIPT
Type-safe class construction within generic class in TYPESCRIPT

Time:02-03

I'm trying to implement a generic function which let's me construct a class with ctor-arguments in a type-safe way.

I tried something like this, but unfortunately it doesn't work:

function createEntity<T>(ctor: new (...args: any[]) => T, ...args: ConstructorParameters<typeof T>): T {
      const entity = new ctor(...args);
      return entity;
}

It complains about "T only refers to a type, but is used as a value here". When converting the generic function to a regular one, replacing the T with a concrete class, it does compile, though when calling the function, invalid argument types are still not properly recognized, it will complain about too many parameters only.

Is there any way to make this work ?

CodePudding user response:

You are only generically capturing the instance type, and you can't get the constructor type from an instance.

You're better off capturing the constructor type and then getting the InstanceType from that.

function createEntity<
    T extends new (...args: any[]) => any
>(
    ctor: T,
    ...args: ConstructorParameters<T>
): InstanceType<T> {
      const entity = new ctor(...args);
      return entity;
}

Which does what you want:

class A {
    constructor(a: number, b: string) {}
}

createEntity(A, 123, 'abc') // fine

See Playground

  • Related