简体   繁体   中英

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)

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.
    }
}

After some diggin in i got next solution:

import * as types from '...';
// then you can use it like so:
jsonWebToken: types.JsonWebToken,

But this solution is dumb and makes me sad. Is this a typescript bug or what?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM