I have a function that takes as parameters a method name as a string and the object that contains that method. I can easily check that the class of the object contains the method name. But I also want to make sure that it is callable and the return type is of a certain type. How can I do that?
type expected = {
a: string;
}
function handle<T>(method: keyof T, handler : T ) {
const f = handler[method];
return f(); // this does not compile
}
class Handler {
foo() {
return 'bar';
}
baz() {
return { a : 'bar'}
}
}
handle('foo', new Handler()); // compile error - not the expected return type
handle('baz', new Handler()); // should compile