I'm trying to create function that calls specified method on some generic object.
This is what I came up with:
type MethodName<S extends Object, M extends keyof S> = S[M] extends Function ? M : never
const callMethod = <S, M extends keyof S>(obj: S, method: MethodName<S, M>) =>
obj[method]()
But I get error this expression is not callable. Even though if I change this function to just returning specified method I can call it later:
const getMethod = <S, M extends keyof S>(obj: S, method: MethodName<S, M>) =>
obj[method]
const obj = {
a: 'hi',
call: () => console.log('hi')
}
getMethod(obj, 'call')
How do I get rid of error in the first case?