primus / eventemitter3

EventEmitter3 - Because there's also a number 2. And we're faster.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Type errors when wrapping emit in a function passing all args

marcelbeumer opened this issue · comments

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

I don't know, I don't use TypeScript.

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;
}

no easy code,no good design。

playground

I guess this is not an issue anymore?

I'm closing this as per @unional's comment. Please comment if this needs to stay open.