MaximilianMairinger
MaximilianMairinger

Reputation: 2424

Typescript: Instance of class type

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.

Upvotes: 5

Views: 12206

Answers (3)

Aron
Aron

Reputation: 9238

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

Upvotes: 5

Lesiak
Lesiak

Reputation: 25936

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)

Upvotes: 1

satanTime
satanTime

Reputation: 13539

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)
}

Upvotes: 1

Related Questions