Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instance type from constructor type

Tags:

typescript

How do you infer the instance type of a class when you're working with the constructor in a literal type?

class Foo {}

let Events = { Foo };

// TypeScript says:
//   typeof Events.Foo === typeof Foo (the constructor)

// I want:
//   typeof Events.Foo === Foo

I'm looking for the equivalent of ReturnType<T> but for getting the instance type, given a constructor function.

Here's a more concrete example:

class Event {}

class FooEvent extends Event {
  type = "foo";
}

class BarEvent extends Event {
  type = "bar";
}

let Events = { FooEvent, BarEvent };

type Handler = {
  [K in keyof typeof Events]?:
    (event: (typeof Events)[K]) => void,
}

let FooHandler: Handler = {
  FooEvent(event: FooEvent) {
    // Type '(event: FooEvent) => void' is not assignable to type '(event: typeof FooEvent) => void'.
    // Types of parameters 'event' and 'event' are incompatible.
  }
};
like image 267
Dan Prince Avatar asked Sep 03 '25 02:09

Dan Prince


1 Answers

You are looking for the built in conditional type InstanceType

class Event { }

class FooEvent extends Event {
    type = "foo";
}

class BarEvent extends Event {
    type = "bar";
}

let Events = { FooEvent, BarEvent };

type Handler = {
    [K in keyof typeof Events]?:
    (event: InstanceType<typeof Events[K]>) => void
}

let FooHandler: Handler = {
    FooEvent(event: FooEvent) {
        event.type
    }
};
like image 124
Titian Cernicova-Dragomir Avatar answered Sep 05 '25 01:09

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!