TypeScript: get type of instance method of class

Viewed 8550

I'm trying to get the type of an instance method of a class. Is there a built-in (better) way other than looking up the type in the prototype of the class?

class MyClass
{
    private delegate: typeof MyClass.prototype.myMethod; // gets the type ( boolean ) => number;

    public myMethod( arg: boolean )
    {
        return 3.14;
    }
}

Thanks in advance!

4 Answers

You could use TypeScript's built in InstanceType for that:

class MyClass
{
  private delegate: InstanceType<typeof MyClass>['myMethod']; // gets the type (boolean) => number;

  public myMethod( arg: boolean )
  {
    return 3.14;
  }
}

you can use the following type:

type TypeOfClassMethod<T, M extends keyof T> = T[M] extends Function ? T[M] : never;

With that, you can write the following:

class MyClass
{
  private delegate: TypeOfClassMethod<MyClass, 'myMethod'>; // gets the type (boolean) => number;

  public myMethod( arg: boolean )
  {
    return 3.14;
  }
}

The simplest and most idiomatic approach appears to be:

type MyMethodType = MyClass['myMethod'];

It does not seem to have any downsides. And, as @cuddlefish points out, it also works if MyClass is generic.

Related