typescript 带有多个参数的React Redux RTK查询在providesTags函数上抛出错误

iyzzxitl  于 2023-04-22  发布在  TypeScript
关注(0)|答案(2)|浏览(188)

我目前正在将React Redux RTK实现到我的React应用程序中,我在获取数据时遇到了问题。
我想创建一个端点,其中查询需要多个参数才能工作。例如,端点是https://localhost:8080/object/id,其中Object和Id是我需要从中获取数据的参数。
我已经为查询创建了一个这样的接口:

export interface ISearch {
    objectName: string,
    id: string
}

我的apiSlice看起来像这样:

import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query";
import {ISearch} from "../utils/Interfaces";

export const apiSlice = createApi({
    reducerPath: 'api',
    baseQuery: fetchBaseQuery({
        baseUrl: 'https://localhost:8080/api/v1'
    }),
    tagTypes: ['Record'],
    endpoints: builder => ({
        getRecord: builder.query({
            query: (params: ISearch) => `/${params.objectName}/${params.id}`,
            providesTags: (result, error, arg) => [{
                type: 'Record',
                id: arg
            }]
        })
    })
})

唯一的问题是我在providesTags函数上得到以下错误:

TS2322: Type '(result: any, error: FetchBaseQueryError, arg: ISearch) => { type: "Record"; id: ISearch; }[]' is not assignable to type 'ResultDescription<"ObjectDefinition" | "Record", any, ISearch, FetchBaseQueryError, FetchBaseQueryMeta>'.   Type '(result: any, error: FetchBaseQueryError, arg: ISearch) => { type: "Record"; id: ISearch; }[]' is not assignable to type 'GetResultDescriptionFn<"ObjectDefinition" | "Record", any, ISearch, FetchBaseQueryError, FetchBaseQueryMeta>'.     Type '{ type: "Record"; id: ISearch; }[]' is not assignable to type 'readonly TagDescription<"ObjectDefinition" | "Record">[]'.       Type '{ type: "Record"; id: ISearch; }' is not assignable to type 'TagDescription<"ObjectDefinition" | "Record">'.         Type '{ type: "Record"; id: ISearch; }' is not assignable to type 'FullTagDescription<"ObjectDefinition" | "Record">'.           Types of property 'id' are incompatible.             Type 'ISearch' is not assignable to type 'string | number'.               Type 'ISearch' is not assignable to type 'number'.
ua4mk5z4

ua4mk5z41#

查询标记由类型和字符串id组成。providesTags函数中的arg就是query函数中的params。因此,您可能希望使用arg.id或类似arg.object + '/' + arg.id的连接字符串,而不是使用arg作为id

qxgroojn

qxgroojn2#

对于任何为此而挣扎的人,我发现了一个小花絮,可能会帮助某人......尝试在标记定义中设置type: 'Record' as const ......似乎在RTK查询中,使用数字动态设置id,而不是在标记定义中使用as const似乎已经创建了类型不等式。

相关问题