react typescript 项目,使用了react-query 包装了下 axios请求,
const useCreate = <T, U>(url: string) => {
// const axios = useAxios()
// const queryClient = useQueryClient()
return useMutation(async (params: T) => {
const data: U = await axios.post(`${url}`, params)
return data
})
}
export const useGetCustomer = (params: PatientId) => {
return useGetOne<InformationType>(
['Customer', params.patientId],
'/activity/UserPortrait/getBasicInformation',
params,
)
}
定义了ts类型
export interface ServiceInformation {
y: number
customerServiceId: string
organizationName: string
customerServiceName: string
counselorName: string
devloperName: string
doctor: string
patientCode: string
doctorStatus: number
}
export interface InformationType {
patientName: string
understandWay: string
presentAddress: string
patientSexName: string
patientAge: string
patientMobile: string
patientTelephone: string
idNumber: string
serviceInformation: ServiceInformation[]
}
实际使用的时候
const { data, isLoading, error } = useGetCustomer({ patientId: id })
const { serviceInformation } = data
总报一个ts错误
类型“InformationType | undefined”上不存在属性“serviceInformation”。ts(2339)
这问题已经困扰一天了。哪位大神有时间给解惑一下, 使用 as any 确实可以消除报错。但是我就想知道为什么报这个错
简单的说,因为
data
包含了undefined
类型,而undefined
类型不含任何属性。Code in TypeScript Playround