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.
  }
};
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
    }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With