Adrian Bannister
Adrian Bannister

Reputation: 523

Use typeof as a parameter type

Let's say I have a class:

public class A {
  foo: string;
}

How do I define a function so that it accepts the type of class and returns an instance of it? Something like this:

function bar<T>(c: typeof T): T {
  return new c();
}

const a: A = bar(A);

Upvotes: 2

Views: 356

Answers (2)

Romain Deneau
Romain Deneau

Reputation: 3061

To complete Daniel's answer:

We can use type Constructor<T = {}> = new (...args: any[]) => T; to be more explicit and indicate arguments for the constructor function (but without static type checking).

type Constructor<T = {}> = new (...args: any[]) => T;

function create<T>(Klass: Constructor<T>, ...args: any[]): T {
    return new Klass(...args);
}

class A0 { }
class A1 { constructor(readonly arg: string) {} }

const a0 = create(A0);
console.log(a0 instanceof A0); // true

const a1 = create(A1, 'arg');
console.log(a1 instanceof A1, a1.arg === 'arg'); // true, true

Result → Run it on the TS playground.

Upvotes: 1

Daniel
Daniel

Reputation: 11182

The TypeScript documentation actually has an example for Using Class Types in Generics:

When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. For example,

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

new() is a constructor function

Upvotes: 2

Related Questions