javascriptnode.jstypescriptnodesioredis

TypeScript same function arguments type with different implementation


I am trying to create a function that iterates through a list of ioredis clients and write the data provided to all of them, at the moment, the function implementation looks like this:

public writeAll(args: any) {
    return this.clients.map((client) => client.set.apply(this, args));
}

But as you can already see, the implementation has two problems:

  1. It is not possible to have type checking in the arguments passed as input. (I would ideally like to retain the same type as the ioredis set function, but just the implementation is different).
  2. The arguments need to be provided as an array.

Is it possible to copy the argument types of ioredis to this function and also not get the arguments as an array?


Solution

  • Use rest parameters and the built-in Parameters type:

    public writeAll(...args: Parameters<Redis["set"]>) {
        return this.clients.map((client) => client.set.apply(this, args));
    }
    

    Playground