3

Is it possible for a class with a generic such as class Foo<A> {} to access A's prototype or use a typeguard on A, or run any sort of logic based on A's type alone - without having been provided the class, interface, or instance to Foo's constructor (i.e. Foo has no constructor or the constructor does not accept an argument of type A)?

There are several answers about accessing the constructor, such as Generic Type Inference with Class Argument but I am only interested in running different logic based on the type, not instantiating a new instance of it.

Specifically, I want to know if A.prototype has a certain method defined on it.

davidkomer
  • 3,020
  • 2
  • 23
  • 58

1 Answers1

0

If your goal is to only allow A classes with a specific function you can use the extends mechanism with generic as well, like this:

interface B {
   myMandatoryFunction()
}

class Foo<A extends B> {
   //...
}

If an action in your Generic class is based on on A having a function or not on its prototype, you will have to instantiate a A object and look at it's prototype because Typescript typing is just involved at compilation and checking type of object during code execution is done exactly like in js with instanceof method and thus is not applicable to types

dekajoo
  • 2,024
  • 1
  • 25
  • 36
  • "will have to instantiate A object" - so the _only_ way is if an instance of A is passed to Foo as an argument? – davidkomer Aug 20 '17 at 06:24