我可以在诺言中键入.then的回调,目前我暂时使用any
位,我想使用string
或类似名称。
有人知道如何键入我的函数md5吗?
export const md5 = (path: string) =>
new Promise((resolve, reject) => {
const hash = createHash("sha1");
const rs = createReadStream(path);
rs.on("error", reject);
rs.on("data", chunk => hash.update(chunk));
rs.on("end", () => resolve(hash.digest("hex")));
});
it("should hash md5 a file", () => {
// error here on hash:string, if I use instead any it works
const m = md5(fileName).then((hash: string) => {
assert.strictEqual(m, "4738e449ab0ae7c25505aab6e88750da");
});
我收到的错误:
Argument of type '(hash: string) => void' is not assignable to parameter of type '(value: {}) => void | PromiseLike<void>'.
Types of parameters 'hash' and 'value' are incompatible.
Type '{}' is not assignable to type 'string'.
});
答案 0 :(得分:2)
考虑直接指定返回的Promise类型new Promise<string>
:
export const md5 = (path: string) =>
new Promise<string>((resolve, reject) => {
const hash = createHash("sha1");
const rs = createReadStream(path);
rs.on("error", reject);
rs.on("data", chunk => hash.update(chunk));
rs.on("end", () => resolve(hash.digest("hex")));
});
还请检查测试中是否有错误,将m
替换为hash
:
assert.strictEqual(hash, "4738e449ab0ae7c25505aab6e88750da");
答案 1 :(得分:1)
或者给Promise一个泛型类型参数,或者给你的md5
方法一个返回类型,或者两者都做:
export const md5 = (path: string): Promise<string> =>
new Promise<string>((resolve, reject) => {
const hash = createHash("sha1");
const rs = createReadStream(path);
rs.on("error", reject);
rs.on("data", chunk => hash.update(chunk));
rs.on("end", () => resolve(hash.digest("hex")));
});
答案 2 :(得分:1)
您所缺少的只是“返回”。更改为此:
export const md5 = (path: string) =>
return new Promise((resolve, reject) => {
const hash = createHash("sha1");
const rs = createReadStream(path);
rs.on("error", reject);
rs.on("data", chunk => hash.update(chunk));
rs.on("end", () => resolve(hash.digest("hex")));
});