Search code examples
typescriptnestjs

How to import type in typescript?


I have following export:

import * as jwt from 'jsonwebtoken';
  ...
export type JsonWebToken = typeof jwt;

Then, i try to use it like so:

export class AuthService {
  constructor(
    @Inject(constants.JWT) private readonly jsonWebToken: JsonWebToken,
    //                                         error here ^  

  ){}

I'm getting this error, that pointing to JsonWebToken:

ReferenceError: jwt_provider_1 is not defined
    at Object.<anonymous> (D:\Learning\nest\project\server\modules\Auth\auth.service.ts:9:59)
    at Module._compile (module.js:573:30)
    at Module.m._compile (D:\Learning\nest\project\node_modules\ts-node\src\index.ts:392:23)
    at Module._extensions..js (module.js:584:10)
    at Object.require.extensions.(anonymous function) [as .ts] (D:\Learning\nest\project\node_modules\ts-node\src\index.ts:395:12)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)

Solution

  • Nest's dependency injection is not designed to work with non-DI types (such as the JWT library). My recommendation would be to make a wrapper component, using the jwt library according to ITS docs, then inject your wrapper to your controllers normally.

    @Component()
    export class JWTComponent {
        signJwt(data) {
            jwt.sign() // etc.
        }
    
        verifyJwt() {
            jwt.verify() // etc.
        }
    }