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!
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.
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.
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.
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;
}
}
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