Issue
I'm trying to create a method that receives as a parameter some method name (as string) of a given class.
So for example if i have this code:
class A {
private member1: string;
public member2: number;
method1() {
//something
}
method2() {
//something
}
propMethod = () => {
//prop method something
}
}
type OnlyClassMethods<T> = T; // need the correct type here
const a = new A();
function callMethod(methodName: OnlyClassMethods<A>) {
// methodName is of type "method1" | "method2"
a[methodName](); // to call this
}
then methodName will be resolved correctly and the intellisense would know that this is indeed a method of A. In reality i'm going to use the method name for mocks, so i'm not really calling it (so this should catch any method regardless of parameters pass or return value) but i still want to ensure that it's only methods that exist on the class.
Edit: I managed to fix my specific issue with both class methods and property methods, but i'll leave the question as is for anyone else. For a solution that could also distinguish between the two types, see Karol Majewski's solution below
Solution
The type you need is this:
type OnlyClassMethods<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never
}[keyof T]
callMethod('method1') // ok
callMethod('foo') // error
callMethod('member1')// error
This is a pretty common mapped type that excludes non-function property names.
Answered By - Nurbol Alpysbayev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.