Typescript: Instance of class type

Viewed 5914

I have the type of a class like here as A_Type?

class A {
  constructor(public a: string) {}
}

type A_Type = {new (a: string): A}

And Id like to get the type of the instance of the A_Type constructor, so that I could type this function explicitly

class A {
  constructor(public a: number) {}
}
//                                              ** not working **
function f<W extends { new(a: number): A }>(e: W): instanceof W {
  return new e(2)
}

let w = f(A)

I am basically searching for the reverse operation of typeof in typescript.

3 Answers

You can use the built in InstanceType<T> utility to do this

class A {
    constructor(public a: number) { }
}

// declare that the return value of the class constructor returns an instance of that class
function f<W extends { new(a: number): InstanceType<W> }>(e: W) {
    return new e(2) // return type is automatically inferred to be InstanceType<W>
}

let w = f(A) // w: A

Playground link

function f<W extends { new(a: number): any }, R extends W extends { new(a: number): infer U } ? U : never>(e: W): R {
  return new e(2)
}

you need to use generics to extract the return type.

But if you always expect an instance of A you can simplify it to

function f<W extends { new(a: number): A }>(e: W): A {
  return new e(2)
}

I would go with the following:

type Constructor<X> = {new (a: number): X}

function f<X>(e: Constructor<X>): X {
  return new e(2)
}

const w = f(A)
Related