提问人:Mehrab 提问时间:10/8/2023 最后编辑:Mehrab 更新时间:10/9/2023 访问量:47
在 mutation 函数中定义 props 的类型
Define type for props in mutation function
问:
我最近在做一个有打字稿和ReactQuery的react项目。 我是打字稿的新手并搜索了它,但不明白在这种情况下如何定义类型:
export interface IPropertyAPI {
useGetProperties: () => {
mutate: (
id: string | undefined,
statusId: string | undefined,
typeId: string | undefined,
rooms: string | undefined,
neighborhood: string | undefined,
district: string | undefined,
priceMin: string | undefined,
priceMax: string | undefined,
createdAtAfter: string | undefined,
createdAtBefore: string | undefined,
ordering: string | undefined,
onSuccess: any,
) => void,
data: any,
isLoading: boolean,
},
useGetDetails: () => {
mutate: (id: string | undefined) => void,
data: any,
}
}
export const propertyAPI: IPropertyAPI = {
useGetProperties: () => useMutation(
'getProperties',
(
ordering,
id,
statusId,
typeId,
rooms,
neighborhood,
district,
priceMin,
priceMax,
createdAtAfter,
createdAtBefore,
) => axios
.get(
`/estates/?offset=20&ordering=${
ordering
}&propertyId${
id
}&statusId${
statusId
}&typeId${
typeId
}&rooms${
rooms
}&neighborhood${
neighborhood
}&district${
district
}&priceMin${
priceMin
}&priceMax${
priceMax
}&createdAtAfter${
createdAtAfter
}&createdAtBefore${
createdAtBefore
}`
),
{
onSuccess: (data) => data,
}
)
错误: TS2322:键入“UseMutationResult<any, unknown, string |undefined, unknown>' 不能分配给类型“{ mutate: (id: string | undefined, statusId: string | undefined, typeId: string | undefined, rooms: string | undefined, neighborhood: string | undefined, district: string | undefined, priceMin: string | undefined, priceMax: string | undefined}'。
你能告诉我为什么我为此出错吗? 或指向答案的链接。
谢谢
我尝试在该界面中定义道具,但由于我对打字稿了解不多,我不知道该怎么做
答:
首先,为参数创建一个类型:
interface Params {
ordering?: string,
id?: string,
statusId?: string,
typeId?: string,
rooms?: string,
neighborhood?: string,
district?: string,
priceMin?: string,
priceMax?: string,
createdAtAfter?: string,
createdAtBefore?: string
}
现在,您可以只使用库公开的类型作为返回值。
export interface IPropertyAPI {
useGetProperties: () => UseMutationResult<Params>
}
该类型实际上需要 4 个泛型参数。第一个是返回的内容,第二个是同一函数将抛出的错误类型。您可以在文档中查找其余部分。UseMutationResult
mutationFn
现在,很可能你不需要显式地给出类型,它应该通过类型推断自动工作。因此,您可以在 mutationFn 中给出类型,然后使用钩子,您应该会得到这些类型。
此外,您可以将第二个参数中的参数作为对象传递给 ,这样您就不需要手动创建字符串:axios.get
axios.get('/estates/', {
params: {
ordering: ''
...
}
})
评论