Search code examples
node.jstypescriptpassport.jspassport-local

pass module as argument in typescript


I am migrating from javascript to typescript.

To keep my code clean I spread my code in seperate files but I am having problem doing that in typescript

Folder structure :

App
 |- config
 |  |- passport.js
 |- server.js

Doing this was totally valid in javascript:

app.js(file)

const passport = require('passport')
const config = require('./config/passport')(passport)
//all other express code

config.js(file)

const config = (passport)=>{
//authentication login
}
module.exports = config

but when I try to do something similar in typescript

app.ts(file)

import express from 'express'
import config from './config/passport'
//all other express code

config.ts(file)

const config = (passport)=>{
//authentication login
}
export default config

I get this error

Parameter 'passport' implicitly has an 'any' type

I know I can pass passport:any as a parameter to config function but I want type checking here

I also tried

import passport from 'passport'
let passportType = typeof passport
config(passport : passportType) 

but get this error

'passportType' refers to a value, but is being used as a type here.


Solution

  • In your last example let passportType = typeof passport is creating a Javascript variable passportType with value "object". It's confusion because both Javascript and Typescript have a typeof operator with different meanings.

    In order to create a Typescript type, you would need to use the keyword type instead of let.

    import passport from 'passport'
    
    type PassportType = typeof passport
    
    const config = (passport: PassportType) => {
    

    It is a bit strange that you are passing the entire passport module to a function rather than just using the imported passport in the config file.