繁体   English   中英

如何为Flow注释此功能

[英]How do I annotate this function for Flow

我在使用Flow( https://github.com/facebook/flow )的文件中有此JS函数

// @flow
static promiseWrapper(fn, ...args) {
  return new Promise(
    async function(resolve, reject) {
      try {
        await fn(...args);
        resolve();
      } catch (e) {
        reject(e);
      }
    }
  )
}

我将如何注释呢?

正如在github项目问题上讨论的那样,这是我建议的解决方案:

class Foo {
  // We are using generics <U, T> to define the input type / output type (may be the same... I don't know the use-cases)
  static promiseWrapper<U, T>(fn: (...args: Array<U>) => Promise<T>, ...args: Array<U>): Promise<T> {
    return new Promise(async (resolve, reject) => {
      try {
        // I felt like handling the return value of this await function
        const ret = await fn(...args);
        resolve(ret);
      } catch (e) {
        reject(e);
      }
    });
  }
}


// Most of the type inference comes from this function
function fun(...args: Array<number>): Promise<string> {
  const ret = args.reduce((result, num) => (result + num), 0);
  return Promise.resolve(ret.toString());
}

const myProm = Foo.promiseWrapper(fun, 1, 2, 3);

// Here, total should be inferred as string, since our `fun` function returns a Promise<string>
// Generic function definition <T> picks this up correctly :-)
myProm.then((total) => {
  // $ExpectError : total should be inferred as string, hence it should fail on numerical addition
  const foo: number = total + 1;

});

暂无
暂无

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

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