近期使用 Typescxript 搭配 Axios 使用,有用攔截器加上一些客製化的回傳值。雖說 JavaScript 是可行,但 TypeScript 的型別判斷就會出錯。這邊筆記下解決這個狀況的方法。
概念
1. 宣告一個自定義的 d.ts 檔案,用來擴展 interface
2. 由於 Interface 本身是 open 的:當相同的 interface 出現時,內部的值會被合併。運用這個性質,可用最小程度覆蓋 axios 的定義檔。
程式碼
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**
* Axios customized types
*/
import 'axios'
declare module 'axios' {
export interface AxiosRequestConfig {
permissions?: string[]
}
export interface AxiosResponse{
target?: any;
}
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Axios customized types | |
*/ | |
import 'axios' | |
declare module 'axios' { | |
export interface AxiosRequestConfig { | |
permissions?: string[] | |
} | |
export interface AxiosResponse{ | |
target?: any; | |
} | |
} |
參考資料
1. [TS] Interfaces
2. 扩展 axios AxiosResponse 接口返回值字段
3. How to use Axios with TypeScript when using response interceptors (AxiosResponse issue)