Type errors when wrapping emit in a function passing all args
marcelbeumer opened this issue · comments
Marcel Beumer commented
How to achieve the following with EventEmitter? Thanks!
import EventEmitter from 'eventemitter3';
export interface Events {
start: [{}];
stop: [{}];
error: [{ error: Error }];
}
function addLogging<T extends (...args: any[]) => any>(
fn: T
): (...args: Parameters<T>) => ReturnType<T> {
return (...args) => {
console.log('Add some logging');
return fn(...args);
};
}
const otherFn = (a: number, b: number) => a * b;
const otherFnLogged = addLogging(otherFn);
const eventEmitter = new EventEmitter<Events>();
const emitLogged = addLogging(eventEmitter.emit);
otherFnLogged(1, 2); // fine
otherFnLogged(1, 2); // fine
eventEmitter.emit('start', {}); // fine
emitLogged('start', {}); // <-- error because TS says its (...args: never) => boolean
Luigi Pinca commented
I don't know, I don't use TypeScript.
Nam Nguyen commented
We can return the type T
directly:
function addLogging<T extends Function>(fn: T): T {
function withLogging(...args: unknown[]) {
console.log('Add some logging');
return fn(...args);
}
return withLogging as any;
}
lemonker commented
no easy code,no good design。
Homa Wong commented
I guess this is not an issue anymore?
Luigi Pinca commented
I'm closing this as per @unional's comment. Please comment if this needs to stay open.