Many Q&As discuss creating a function wrapper in TypeScript, but my question is how to do the same with named methods. I am interested in writing something similar to this JavaScript code:
function wrap(API, fnName, fn) {
const origFn = API.prototype[fnName];
API.prototype[fnName] = function(...args) {
fn(...args);
return origFn.call(this, ...args);
};
}
wrap(CanvasRenderingContext2D, 'fillRect', function(x, y, w, h) {
console.log(x, y, w, h);
});
// --- check it worked ---
const ctx = document.querySelector('canvas').getContext('2d');
ctx.fillRect(10, 20, 100, 40);
<canvas></canvas>
Additionally, I would like to be able to use lists of functions or functions on objects like this:
function wrap(API, fnName, fn) {
const origFn = API.prototype[fnName];
API.prototype[fnName] = function(...args) {
fn(...args);
return origFn.call(this, ...args);
};
}
const wrappers = {
fillRect(x, y, w, h) {
console.log('fill:', x, y, w, h);
},
strokeRect(x, y, w, h) {
console.log('stroke:', x, y, w, h);
},
};
for (const [name, fn] of Object.entries(wrappers)) {
wrap(CanvasRenderingContext2D, name, fn);
}
// --- check it worked ---
const ctx = document.querySelector('canvas').getContext('2d');
ctx.fillRect(10, 20, 100, 40);
ctx.strokeRect(40, 70, 20, 40);
<canvas></canvas>
Is it possible to write either of these forms in a type-safe manner in TypeScript? Can the function associated with the method match types based on the names of the functions?
Note: In my actual scenario, the functions will perform more than just console.log
and will need to ensure they are using the types correctly.