I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy
around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running into some issues with types that are causing headaches. While similar in concept to another question I posted (Writing wrapper to third party class methods in TS), this approach is different based on feedback I received.
Currently, I'm facing an error message:
Element implicitly has an 'any' type because expression of type 'string | symbol' can't be used to index type 'API'. No index signature with a parameter of type 'string' was found on type 'API'
. It makes sense since sayHello
isn't strictly considered a string
in TypeScript, but I'm unsure of the best way to access methods on this class without using property accessor notation.
class API {
sayHello(name: string) {
console.log(“hello “ + name)
return name
}
}
export default <T extends API>(
api: T,
) =>
new Proxy(api, {
get(target, prop) {
if (typeof target[prop] !== "function") {
return target[prop];
}
return async (...args: Parameters<typeof target[prop]>) => {
try {
const res = await target[prop](...args);
return res
} catch (e) {
}
};
},
});
Can this be achieved in TypeScript?