当前位置:问答中心开发实战typescript 一直提示 类型 不存在属性?

typescript 一直提示 类型 不存在属性?

0
音拂 提问于 2年 前

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)

typescript 一直提示 类型 不存在属性?

这问题已经困扰一天了。哪位大神有时间给解惑一下, 使用 as any 确实可以消除报错,但是我就想知道为什么报这个错。

2 人参与回答
0
Best Answer
码云 管理员 发布于 2年 前
export interface ServiceInformation {
    customerServiceId: string
}

export interface InformationType {
    serviceInformation: ServiceInformation[]
}


function test1(a?: InformationType) {
    // Property 'serviceInformation' does not exist on type 'InformationType | undefined'.
    const { serviceInformation } = a;

    // 这个是对的,但类型是 ServiceInformation[] | undefined
    const another = a?.serviceInformation;
}

简单的说,因为 data 包含了 undefined 类型,而 undefined 类型不含任何属性。
Code in TypeScript Playround

音拂 回复于 2年 之前

首先,感谢回答,这个错是由于useGetCustomer返回的是一个promise,可能为 可能为undefined。我消除ts报错的方法是在引用的时候赋一个默认值,感觉也挺呆的,不知道还有没有更好的办法,

const { data = { serviceInformation: {} }, isLoading, error } = useGetCustomer({ patientId: id })

0
音拂 发布于 2年 前

引用的时候赋一个默认值,可消除 ts 错误

const { data = { serviceInformation: {} }, isLoading, error } = useGetCustomer({ patientId: id })