我想将 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 的两个问题:
ESLint:避免引用未绑定(bind)的方法,这可能会导致无意中在
this.redisClient.get
片段中确定“this”的范围。(@typescript-eslint/unbound-method)
和
ESLint:任意值的不安全赋值。(@typescript-eslint/no-unsafe-assignment)
atgetAsync
如何以类型感知和正确的 this
范围的方式使用 promisify
?
最佳答案
在第一个 eslint 错误中,您将 this
绑定(bind)到了错误的方法。
在第二个错误中,您告诉 Typescript getAsync 应该保存什么返回类型,而您需要告诉 promisify
您尝试 promise 的返回值是什么.
这应该可以修复两个 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))
};
}
关于typescript - Redis 客户端中的 Promisify 违反了 eslint 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66472406/