我們先來看下以下代碼
export const http = async (endpoint: string, { data, token, headers, ...customConfig }: Config) => {
// xxx
// xxx
}
export const useHttp = () => {
// 這里可以優(yōu)化的地方 [string, Config] 這個類型其實與我們定義的函數(shù)http的類型是一模一樣的
// 有沒有一種方法讓我們直接從http函數(shù)獲取的入?yún)⒌念愋停皇切枰貜?fù)寫一遍
// 有呀毁嗦,那就是通過 Parameters<typeof http> 來解決,拿到http的類型
return ([endpoint, config]: [string, Config]) => {
// xxx
}
}
我們看到的上面的代碼回铛,以及注釋狗准,我們的目的就是想快速拿到函數(shù)http
入?yún)⒌腡S類型克锣,解決方案如下
export const useHttp = () => {
const { user } = useAuth()
// 這里可以優(yōu)化的地方 [string, Config] 這個類型其實與我們定義的函數(shù)http的類型是一模一樣的
// 有沒有一種方法讓我們直接從http函數(shù)獲取的入?yún)⒌念愋停皇切枰貜?fù)寫一遍
// 有呀腔长,那就是通過 Parameters<typeof http> 來解決袭祟,拿到http的類型
// return ([endpoint, config]: [string, Config]) => {
// http(endpoint, { ...config, token: user?.token })
// }
return ([endpoint, config]: Parameters<typeof http>) => {
http(endpoint, { ...config, token: user?.token })
}
}
使用Parameters<typeof http>
解決