passport.js - 使用 Typescript 的 Passportjs
我正在尝试在一个 TypeScript 项目中使用 passport。在所有示例中,done 回调函数都是用 null 值调用的。但我得到了 TypeScript 错误 Argument of type 'null' is not assignable to parameter of type 'string | Error | undefined'。我可以使用 done(null as any, profile); 让它工作。问题可能出在 @type/passport 上。我在谷歌搜索了这个问题,但没有找到任何信息,所以我猜可能是我做错了什么(我不认为我是唯一一个在 TypeScript 中使用 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);
}));
答案#1
回调函数的常见格式是 callback(error: Error | string | undefined, successData: SpecifiedType),这意味着当你遇到错误情况时,第一个参数可以传递一个 Error 对象,或者只是描述错误原因的普通字符串。如果没有错误,你可以传递 undefined。由于在回调函数实现中通常会检查 if(error),任何假值(例如 null)都可以起作用。
由于你正在使用 Typescript,它会推荐使用库作者设计的方式来接收回调中错误参数的 falsy 值,这个值是 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 是一样的。如果你深入源码,我敢打赌你能找到错误是如何处理的。但是,只要错误是 falsy,这无关紧要。
