Passportjs with Typescript

Viewed 470

I'm trying to use passport in a typescript project. In all of the example the done callback function is called with the null value. But I get the typescript error Argument of type 'null' is not assignable to parameter of type 'string | Error | undefined'. I can make it work using done(null as any, profile);. The problem is probably with @type/passport. I googled this this problem, but didn't find anything, so I'm guessing that I did something wrong (I don't think I'm the only person using typescript with 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 Answers

The common format of callback functions is callback(error: Error | string | undefined, successData: SpecifiedType) which means when you encounter an error condition, the first parameter could be passed as an Error object or just plain string describing the reason of the error. If there is no error you can pass undefined. Since it is common to check if(error) in the callback function implementation, any falsy value such as null would do the job.

Since you are using Typescript, it is recommending you the way the library author intended to receive the falsy value for the error parameter in the callback, and it is undefined. So, in your case, you may return done(undefined, profile); without any issue.


Just to ensure that undefined is fine when there is no error, I had a look at the Google Strategy test case here: 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();
      });

You see, done is passing nothing, which is same as passing undefined. If you dig into source, I bet you could find where error is handled. But, it does not matter as long as error is falsy.

Related