一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情。
先看一下问题
const res = await request.post('/authorizations', values)
console.log(res.data.) // 这里的点没有提示
我希望我每次都能res.data接着后面能点出响应的数据,这样我写的很方便,并且也不容易出错,所以需要在TS中配置axios的返回值的类型
因为响应的数据都是message和data,而我们需要的是data里面的数据,但是data又不是固定的,每一个响应的数据都是不一样的,所以这里需要用到泛型接口
在data.d.ts文件下(这个文件一般用来存放各个接口的类型)定义好axios返回值的类型的类型
// 泛型函数,接口,类
export interface ApiResponse<T> {
//基本上响应数据里的message都是string类型
message:string,
//但是data的类型是变化的,所以我们不能写死,需要传给axios
data:T
}
然后定义响应数据的类型,一般接口文档上就会有,或者发送请求获取到数据打印出来也可以
接口文档上的比如用户的信息
然后我们根据接口文档上的类型,在data.d.ts文件下定义好用户信息的data的类型
export type UserProfile = {
id: string
photo: string
name: string
mobile: string
gender: number
birthday: string
intro: string
}
然后再actions/user模块里发请求时设置axios的响应类型
//先导入在data.d.ts里定义的类型
import { ApiResponse, UserProfile } from '@/types/data'
//RootThunkAction发送异步请求时需要的
export const getUserProfile = ():RootThunkAction => {
return async (dispatch) => {
//在请求方式后面加上接口泛型ApiResponse,并把我们定义的UserProfile当做参数传入
const res = await request.get<ApiResponse<UserProfile>>('/user/profile')
dispatch({
type: 'profile/getUserProfile', payload: res.data.data
})
}
}
传入ApiResponse告诉ts这个请求的返回值里有message和data,其中message是string类型,data是我定义好并且传入的UserProfile类型,这样我们接收的res.data后面就可以接着点了,并且类型会跟后端响应的一样,基本不会出错