简体   繁体   English

如何在打字稿中键入诺言的回调?

[英]How to type the callback of a promise in typescript?

I can type the callback for .then in my promise, currently I am temporary using any bit I would like to use string or similar. 我可以在诺言中键入.then的回调,目前我是临时使用我想使用string或类似string any位。

Any idea how to type my function md5? 任何想法如何键入我的功能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");
    });

Error I receive: 我收到的错误:

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'.
  });

Consider specifying the return Promise type directly new Promise<string> : 考虑直接指定返回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")));
  });

Please also check for an error in your test, replace m with hash : 另请检查测试中是否有错误,将m替换为hash

assert.strictEqual(hash, "4738e449ab0ae7c25505aab6e88750da");

Either give the Promise a generic type parameter, give your md5 method a return type, or both: 要么给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")));
  });

All you are missing is 'return'. 您所缺少的只是“返回”。 Change to this: 更改为此:

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")));
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM