简体   繁体   English

如何在打字稿中注释生成器函数

[英]How to annotate generator functions in typescript

Let's look at the example async function from promisejs.org , which is allows us to wait for promises using generators: 让我们看看promisejs.org中的示例async函数,它允许我们使用生成器等待promises:

function async(makeGenerator){
  return function () {
    var generator = makeGenerator.apply(this, arguments);

    function handle(result){
      // result => { done: [Boolean], value: [Object] }
      if (result.done) return Promise.resolve(result.value);

      return Promise.resolve(result.value).then(function (res){
        return handle(generator.next(res));
      }, function (err){
        return handle(generator.throw(err));
      });
    }

    try {
      return handle(generator.next());
    } catch (ex) {
      return Promise.reject(ex);
    }
  }
}

Example usage: 用法示例:

var login = async(function* (username, password, session) {
  var user = yield getUser(username);
  var hash = yield crypto.hashAsync(password + user.salt);
  if (user.hash !== hash) {
    throw new Error('Incorrect password');
  }
  session.setUser(user);
});

My question: How should both of these functions be annotated in TypeScript, in orded to keep type safety? 我的问题:如何在TypeScript中注释这两个函数,以保持类型安全?

What I've tried: I know the async function returns a Promise<T> , but I'm not sure what T should be. 我试过的:我知道async函数返回一个Promise<T> ,但我不确定T应该是什么。 I guess it should depend on the generator passed in, but what type does a generator have? 我想这应该取决于传入的发电机,但发电机有什么类型? There is GeneratorFunction in the typings for nodejs or bluebird (can't remember which), but that one is not generic so I can't do async(makeGenerator: GeneratorFunction<T>): Promise<T> as I'd want to. nodejs或bluebird的输入中有GeneratorFunction (不记得哪个),但那个不是通用的,所以我不能做async(makeGenerator: GeneratorFunction<T>): Promise<T>因为我想要。

but I'm not sure what T should be 但我不确定T应该是什么

In your case login returns nothing to Promise<void> . 在您的情况下, login不向Promise<void>返回任何内容。

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

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