I am facing an issue with a function that retrieves a property from an object.
// Utils.ts
export function getProperty<T, K extends keyof T>(obj: T, key: string): T[K] {
if (key in obj) { return obj[key as K]; }
throw new Error(`Invalid object member "${key}"`);
}
My aim is to verify if the returned property is a function with a specific signature and then proceed to call this property with a provided parameter.
The function getProperty()
is utilized for dynamically fetching one of the object's methods and invoking it. I attempted the following:
let property: this[keyof this] = utils.getProperty(this, name);
if (typeof property === 'function') ) { property(conf); }
However, I encountered an error stating "Cannot invoke an expression whose type lacks a call signature. Type 'any' has no compatible call signatures." I acknowledge that the property retrieved by getProperty()
can technically be of any type, but how can I ensure that it specifically conforms to a function with the signature (conf: {}): void
?