typescriptevent-bus

Spread argument in Typescript


I'm making a EventBus in typescript, react. But there is a type error in my code.

This is my code.

class _EventBus {
  private readonly bus: { [key: string | number]: () => void }
  constructor() {
    this.bus = {}
  }

  $off(id: string | number) {
    delete this.bus[id]
  }

  $on(id: string | number, callback: () => void) {
    this.bus[id] = callback
  }

  $emit(id: string | number, params: Array<string | number>) {
    if(this.bus[id]) {
      this.bus[id](...params) // A spread argument must either have a tuple type or be passed to a rest parameter.
    }
  }
}

export const EventBus = new _EventBus()

The callback parameter has an error A spread argument must either have a tuple type or be passed to a rest parameter.

And I also tried this code.

private readonly bus: { [key: string | number]: (params: Array<string | number>) => void }

But this code has an eslint error no-unused-vars.

How can I make a event-bus like vue in typescript, react?


Solution

  • You need to change the type definition of the bus field to the following

    private readonly bus: {
      [key: string | number]: (...params: Array<string | number>) => void;
    };
    

    You can find the working example in this sandbox

    And the link to the TypeScript Rest Parameters and Arguments