2

我想使用 redis 客户端promisify

import type { RedisClient } from "redis";
import * as util from "util";

class MyClass {
  private redisClient: RedisClient;

  constructor(client: RedisClient) {
    this.redisClient = client;
  }

  getMyData = (): SomeType[] => {
    const getAsync: Promise<string | undefined> = util.promisify(this.redisClient.get).bind(this.redisClient);
 // ...
  };
}

但是我遇到了 eslint 的两个问题:

  1. ESLint: Avoid referencing unbound methods which may cause unintentional scoping of 'this'.(@typescript-eslint/unbound-method)this.redisClient.get片段

  1. ESLint: Unsafe assignment of an any value.(@typescript-eslint/no-unsafe-assignment)getAsync

我如何promisify以一种可以识别类型和适当this范围的方式使用?

4

1 回答 1

3

在您的第一个 eslint 错误中,您绑定this到了错误的方法。

在第二个错误中,您告诉 Typescript getAsync应该保留什么返回类型,而不是您需要告诉promisify您试图承诺的返回值是什么。

这应该修复两个 eslint 错误:

import type { RedisClient } from "redis";
import * as util from "util";

class MyClass {
  private redisClient: RedisClient;

  constructor(client: RedisClient) {
    this.redisClient = client;
  }

  getMyData = (): SomeType[] => {
    const getAsync = util.promisify<string |undefined>(this.redisClient.get.bind(this.redisClient))

  };
}
于 2021-03-04T10:34:21.317 回答