There is a suggestion already posted on microsoft/TypeScript#22063 proposing to allow function statements and method definitions to be typed using a function/callable type alias or interface. Currently, there doesn't seem to be much progress on this, but if you feel strongly about it, consider showing your support by giving it a thumbs up or leaving a comment.
If that feature is not available, an alternative could be creating an interface that must be implemented by your class:
type LibDoStuffMethodType = (x: string, y: number) => boolean
interface DoStuffMethod { doStuff: LibDoStuffMethodType };
class MyApp implements DoStuffMethod {
doStuff(a: string, b: number) {
return true;
// delegate to external library's lib.doStuff
}
}
declare const myApp: MyApp;
myApp.doStuff; // now functions as a method
The class MyApp
now includes a legitimate method named doStuff
, but it is restricted to the type LibDoStuffMethodType
!
While this approach works to a certain extent, it may be frustrating that you have to explicitly define the method's parameters and return type. It would be ideal if these could be inferred from the DoStuffMethod
interface automatically, but unfortunately, this is not currently possible (see microsoft/TypeScript#1373). Therefore, any straightforward solution will likely involve some repetition.
Is there a way around this? If LibDoStuffMethodType
is a specific single function type without overloads or generics, you can utilize the Parameters<T>
and ReturnType<T>
utility types for programmatically annotating the parameter list and return type:
class MyApp implements DoStuffMethod {
doStuff(...args: Parameters<LibDoStuffMethodType>): ReturnType<LibDpStuffMethodType> {
return true;
// delegate to external library's lib.doStuff
}
}
This does help with keeping the code DRY, but there are several caveats to consider, making it potentially unsuitable for your needs. Other workarounds may exist, but they might encounter similar limitations.
This represents the closest approximation I could achieve.