Home > other >  Spread argument in Typescript
Spread argument in Typescript

Time:06-08

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?

CodePudding user response:

The error message is pretty much on point here. You can solve this problem by using a rest parameter as the argument of the function.

private readonly bus: { [key: string | number]: (...args: (string | number)[]) => void }

Playground

CodePudding user response:

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

  • Related