typescript - 在 redis 客户端中使用 Promisify 违反 eslint 规则
我想使用带有 promisify 的 redis 客户端:
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:避免引用未绑定的方法,这可能会导致‘this’的意外作用域。(@typescript-eslint/unbound-method)位于this.redisClient.get片段
和
ESLint:不安全地分配了 any 类型的值。(@typescript-eslint/no-unsafe-assignment)在getAsync
我如何使用 promisify,以便它具有类型感知并正确处理 this 的作用域?
答案#1
在你的第一个 eslint 错误中,你将 this 绑定到了错误的方法上。
在第二个错误中,你告诉 Typescript getAsync 应该持有的返回类型,而实际上你需要告诉 promisify 你想要 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))
};
}
