Passport Authenticator complains of that 'this' could be instantiated with an arbitrary type

Viewed 135

I'm trying to type a function to accept both local and general passport authenticator. Unfortunately I'm getting a "this" Typescript error:

import { Passport, Authenticator } from 'passport';

const alternativePassport: Authenticator = new Passport();

Causes the error:

Type 'import("/home/max/workspace/npm/graphql-passport/node_modules/@types/passport/index").Authenticator<import("/home/max/workspace/npm/graphql-passport/node_modules/@types/express/index").Handler, any, any, import("/home/max/workspace/npm/graphql-passport/node_modules/@types/passport/index").AuthenticateOptions>' is not assignable to type 'import("/home/max/workspace/npm/graphql-passport/node_modules/@types/passport/index").PassportStatic.Authenticator<import("/home/max/workspace/npm/graphql-passport/node_modules/@types/express/index").Handler, any, any, import("/home/max/workspace/npm/graphql-passport/node_modules/@types/passport/index").Authenticate...'.
  The types returned by 'use(...)' are incompatible between these types.
    Type 'Authenticator<Handler, any, any, AuthenticateOptions>' is not assignable to type 'this'.
      'this' could be instantiated with an arbitrary type which could be unrelated to 'Authenticator<Handler, any, any, AuthenticateOptions>'.ts(2322)
const alternativePassport: Authenticator<express.Handler, any, any, passport.AuthenticateOptions>
No quick fixes available

Minor note: In the real code I want to pass the alternativePassport into a function with an optional passport object that is assigned to the passport.default export if object isn't provided.

1 Answers

There seems to be an issue with either the typings of Passport or some underlying issue with Authenticator. To be honest, I'm not sure what TS is complaining about, when I redefine the type exactly as it was before, just re-declaring use and unuse the error goes away. My only guess is that passport overlays the Authenticator interface somewhere or there is a typescript bug:

interface WorkingAuthenticator<
  InitializeRet = express.Handler,
  AuthenticateRet = any,
  AuthorizeRet = AuthenticateRet,
  AuthorizeOptions = AuthenticateOptions
> extends Omit<Authenticator<InitializeRet, AuthenticateRet, AuthorizeRet, AuthorizeOptions>,  'use' | 'unuse'> {
  // This is exactly the same as the `Authenticator` interface
  use(strategy: Strategy): this;
  use(name: string, strategy: Strategy): this;
}

const auth: WorkingAuthenticator = new Passport();

An issue on the passport Github page is probably the way to go here, you can use the WorkingAuthernticator type until the issue is fixed or maybe somebody working on passport knows why this error occurs.

Related