Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: get type of instance method of class

Tags:

typescript

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!

like image 380
Markus Mauch Avatar asked Jul 20 '17 08:07

Markus Mauch


People also ask

How do you check TypeScript type?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

How do you find the return type of a function in TypeScript?

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.

How do you define a function in class TypeScript?

A constructor is a special function of the class that is responsible for initializing the variables of the class. TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class.


1 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;
  }
}
like image 179
ronif Avatar answered Sep 21 '22 04:09

ronif