How to import the jwt-decode type definition into Typescript (Ionic 2)

peterc picture peterc · Jan 24, 2017 · Viewed 24.2k times · Source

Just when I think I have the Typings in Typescript under control I come across something that proves the opposite.

This time I am trying to use the jwt-decode. I have installed the type definition via the command typings i dt~jwt-decode --save

Two problems

1. When I look into the index.d.ts I see the following

    declare module 'jwt-decode' {
        namespace JwtDecode {
        interface JwtDecodeStatic {
            (token: string): any;
        }
    }

    var jwtDecode: JwtDecode.JwtDecodeStatic;
    export = jwtDecode;
    export as namespace jwt_decode;
    }

The IDE (VS Code) is displaying an error "[ts] Global module exports may only appear at top level" under the last line export as namespace jwt_decode;

2. How do I import this?

I try the import statement..

   import { ??  } from 'jwt-decode';

but I can't see anything to import.

None of the other (many) examples I can find seem to help. It must be simple, I just don't know the syntax.

Thanks in advance for any help.

[UPDATE] After some more reading, it looks like typings has been superseded by just using npm..

So I tried

npm install --save jwt-decode
npm install --save @types/jwt-decode

// and import via
import * as JWT from 'jwt-decode';

But still can't get it to import correctly.

[UPDATE2] I can add the statement let t = jwt-decode("aaa"); and see the signature, but have the following IDE error

[ts] 'jwt_decode' refers to a UMD global, but the current file is a module. Consider adding an import instead.

Answer

Ernesto Campohermoso picture Ernesto Campohermoso · May 17, 2017

The solution that worked for me was:

npm install --save jwt-decode
npm install --save @types/jwt-decode

// and import via
import * as JWT from 'jwt-decode';

// use JWT() for decode. Not jwt-decode() !!
let t = JWT(token);