1

Let's say I have a typescript class A, and a class B that extends A

class A {
  static a(): number { return 10; }
  a_(): number { return 10; }
}

class B extends A {
  static b(): number { return 20; }
  b_(): number { return 20; }
}

I would like to define a generic typescript interface, like so:

interface ClassAndInstance<C extends A> {
  c: ClassType<C>
  i: C
}

(Note: ClassType here refers to the class (not instance) of the generic type.)

Now, if I have an instance of the ClassAndInstance

ci: ClassAndInstance<B>;

I want to be able to call both the class and the instance fields of B, like so:

ci.c.a();  // 10
ci.c.b();  // 20
ci.i.a_(); // 10
ci.i.b_(); // 20;

How would I define ClassType to achieve this in a type safe manner?

I've chosen an interface to define the semantics behind ClassAndInstance, but if there's any other way of achieving this, that would work too.

ironstein
  • 416
  • 8
  • 23
  • Does [this](https://tsplay.dev/mMROZW) work for you? The instance type `B` doesn't know anything about its constructor type `typeof B`, but the constructor type does know about the type it constructs. So you will need to do `ClassAndInstance` and not `ClassAndInstance`, if that's okay. Let me know if you want to see this written up as an answer. – jcalz Aug 21 '21 at 01:46
  • @jcalz oh that’s smart, instead of passing in the instance type, and trying to infer the class type from it, you directly pass in the class type. How clever! ;) – ironstein Aug 21 '21 at 03:59
  • This definitely works for me, feel free to post this as an answer and I’ll happily accept it :) thanks!! – ironstein Aug 21 '21 at 04:03

0 Answers0