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

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)

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

阅读 14k
3 个回答
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

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

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

原因已选答案已经说了。

没用过这个react-query,不过显而易见useMutation返回的是联合类型
react中一般这样用:

  const mutation = useMutation(() => {
    return new Promise<InformationType>((resolve, reject) => {
      resolve({} as any);
    });
  });

  if (mutation.isSuccess) {
    console.log(mutation.data.serviceInformation);
  } else {
    // mutation.data is undefined
  }

  //
  return (
    <>{mutation.isSuccess ? mutation.data.serviceInformation : "loading"}</>
  );

废话分割线

人生苦短,我用recoil

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏