首页 > 解决方案 > 带有打字稿的 Passportjs

问题描述

我正在尝试在打字稿项目中使用护照。在所有示例中,done回调函数都是使用该null值调用的。但我收到打字稿错误Argument of type 'null' is not assignable to parameter of type 'string | Error | undefined'。我可以使用done(null as any, profile);. 问题可能出在@type/passport. 我用谷歌搜索了这个问题,但没有找到任何东西,所以我猜我做错了什么(我认为我不是唯一一个使用带有护照的打字稿的人)。

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID as string,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
  callbackURL: process.env.CALLBACK_URL
}, function (accessToken, refreshToken, profile, done) {
  return done(null, profile);
}));

标签: typescriptpassport.js

解决方案


回调函数的常见格式是callback(error: Error | string | undefined, successData: SpecifiedType),这意味着当您遇到错误情况时,第一个参数可以作为Error对象传递,也可以只是描述错误原因的纯字符串。如果没有错误可以通过undefined。由于检查if(error)回调函数实现是很常见的,因此任何虚假值null都可以完成这项工作。

由于您使用的是 Typescript,因此建议您使用库作者打算在回调中接收错误参数的虚假值的方式,它是undefined. 因此,就您而言,您可能return done(undefined, profile);没有任何问题。


为了确保undefined在没有错误时一切正常,我在这里查看了 Google Strategy 测试用例:https://github.com/jaredhanson/passport-google-oauth2/blob/2399ef47f00b47ac587f056f2f100a2c4db81928/test/strategy.profile。 test.js#L73-L79

      strategy.userProfile('token', function(err, p) {
        if (err) { return done(err); }
        profile = p;
        done();
      });

你看,done什么都没有传递,这和传递是一样的undefined。如果您深入研究源代码,我敢打赌您可以找到处理错误的位置。但是,只要错误是虚假的,就没有关系。


推荐阅读