promisify redis get and return the correct typescript type

Viewed 953

The redis method get from redis node lib has this typescript signature:

export interface Commands<R> {
    get(key: string, cb?: Callback<string | null>): R;
}

If I promisify the method, the signature is lost and the return type become any.

I have tried to set the correct signature in this way:

const client = redis.createClient(redisOption);
const getAsync = promisify<redis.Commands<boolean>['get']>(client.get).bind(client);

but ts lint show some error:

Get the value of a key.

No overload matches this call. Overload 1 of 14, '(fn: CustomPromisify<(key: string, cb?: Callback) => boolean>): (key: string, cb?: Callback) => boolean', gave the following error. Argument of type '(key: string, cb?: Callback) => boolean' is not assignable to parameter of type 'CustomPromisify<(key: string, cb?: Callback) => boolean>'. Property 'promisify' is missing in type '(key: string, cb?: Callback) => boolean' but required in type 'CustomPromisifyLegacy<(key: string, cb?: Callback) => boolean>'. Overload 2 of 14, '(fn: (callback: (err: any, result: (key: string, cb?: Callback) => boolean) => void) => void): () => Promise<(key: string, cb?: Callback) => boolean>', gave the following error. Argument of type '(key: string, cb?: Callback) => boolean' is not assignable to parameter of type '(callback: (err: any, result: (key: string, cb?: Callback) => boolean) => void) => void'.

How set the correct signature?

1 Answers

I just had a similar issue.

Not sure if it's the optimal solution, but what I've done is I extended the RedisClient interface and then overridden the get method type.

import util from "util";
import redis  from "redis";

interface PromiseRedis extends Omit<redis.RedisClient, "get"> {
  get(key: string): Promise<string | boolean> | boolean;
}

const url = "redis://127.0.0.1:6379";
const redisClient:PromiseRedis = redis.createClient(url);
redisClient.get = util.promisify(redisClient.get)

Now the get function returns a Promise.

Related