網站搜尋

angular - 如何將 jwt-decode 類型定義導入到 Typescript(Ionic 2)


就在我以為我已經掌握了 Typescript 的型別時,我遇到了一些證明情況並非如此的東西。

這次我試著使用 jwt-decode。我已經透過指令 typings i dt~jwt-decode --save 安裝了類型定義

兩個問題

1. 當我查看 index.d.ts 時,我看到以下內容

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

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

IDE(VS Code)在最後一行 export as namespace jwt_decode; 下顯示錯誤 "[ts] 全域模組導出只能出現在頂層"

2. 我如何導入這個?

我嘗試了 import 語句..

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

但我看不到任何可以匯入的東西。

我找到的其他(許多)例子似乎都沒有幫助。這一定很簡單,我只是不知道語法。

先感謝您的任何幫助。

[更新] 經過進一步閱讀,看起來 typings 已經被直接使用 npm 所取代。

所以我試了

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

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

但仍然無法正確導入。

[UPDATE2] 我可以加入語句 let t=jwt-decode("aaa"); 並查看簽名,但會出現以下 IDE 錯誤

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

答案#1

對我有效的解決方法是:

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);