ಠ_ಠ
萬事問噗浪
想請問typescript 要如何去取物件裡面的值
(下收詳細)
求大大幫忙,卡好幾天了……
ಠ_ಠ
用的是vue3+quasar+typescript
ಠ_ಠ
是在axios送post出去後要收response的值
ಠ_ಠ
response.data 裡面會有 token 跟 一包 user
ಠ_ಠ
https://images.plurk.com/11EbLUhhyAQbAMWovlimgX.png
ಠ_ಠ
但是token一直取不出來...QQ
提示是寫Property 'token' does not exist on type 'AxiosResponse<any>'
ಠ_ಠ
https://images.plurk.com/2XvWbsT72f4qmiSToe4kPQ.png
ಠ_ಠ
1.試過用 lodash 的 get (不行)
2.試過用JSON.stringify(respose.data) 然後在parse (不行)
ಠ_ಠ
覺得應該是要想辦法加入token到response的interface裡面
但是不知道從何下手
ಠ_ಠ
也有看到這個
How to use Axios with TypeScript when using response...
但是不知道應該要寫在哪裡...
hippo8028
新增一個axios.d.ts 然後在裡面對interface處理?
hippo8028
從那篇issues裡面應該是可以用Declaration Files去解
hippo8028
https://images.plurk.com/7AZ3OyrVlD41M73i1Nsr0v.png https://images.plurk.com/34U4C8RsHxQlsShO3qkTvh.png
這兩個可以參考一下,或是用Declaration Files關鍵字去找一下Will保哥的blog~
ಠ_ಠ
hippo8028: 感謝hippo!!! 我去找一下QQQQ!!
pepper5704
hacky 的方法是 (response.data as any).token
pepper5704
或是 declear data 的形式,假設是叫 Data,那整個response 的type定義成AxiomResponse<Data>, response.data就會是Data type
hippo8028
噗主的想法應該是沒錯,就是原本的AxiosResponse interface 沒有token,我提供的方法是用*.d.ts declare module去擴充AxiosResponse這樣的感覺XD
載入新的回覆