相同Endpoint有不同响应时的RTKQuery类型定义

问题描述 投票:0回答:1

我是打字稿新手。

我有查询端点,这个查询根据不同的参数给我不同的响应,如下所示:


export type RecentScore = { ndays: number | ''; score: number | '' };

export type TradeScore = {
    startValue: number | '';
    score: number | '';
};

export interface IGetIndices {
    id: number;
    name: string;
    issuerAccountId: number;
    isDefault: boolean;
    startDate: Date;
    createdAt: Date;
    updatedAt: Date;
}

export interface IGetTradeVolume extends IGetIndices {
    scores: { M: TradeScore[] };
}

export interface IGetRecent extends IGetIndices {
    scores: { R: RecentScore[] };
}


getIndices: builder.query<
            IGetTradeVolume[] | IGetRecent[],
            { page: number; size: number; filter: string }
        >({
            query: ({ page, size, filter }) => ({
                url: `/club/indices?${ParamsHandler({ page, size, filter })}`,
                method: 'GET'
            }),
            providesTags: (result) => {
                return result
                    ? [...result.map(({ id }) => ({ type: 'Club' as const, id })), 'Club']
                    : ['Club'];
            }
        })

通过发送不同的

filter
我得到不同形状的对象数组。 当我在组件中使用
useGetIndicesQuery
钩子时,打字稿会警告我某些不存在于
IGetTradeVolume
类型但存在于
IGetRecent
中的文件,反之亦然。

如何正确使用类型以及如何输入

useGetIndicesQuery

我应该为此事创建不同的端点吗?

typescript react-hooks react-typescript rtk-query react-tsx
1个回答
0
投票

不确定我是否理解正确,但在使用查询时需要转换类型,或者应用某种保护。仅从查询来看,并不清楚返回的是

IGetTradeVolume[]
还是
IGetRecent[]
,因此 typescript 假设它是两者之一,这意味着您只能访问共享属性。

选项 1:投射响应

const { data } = useGetIndicesQuery({ ... });
// use a cast if you are certain about the return type
const getTradeVolumes = data as IGetTradeVolume[];

选项 2:使用防护装置

const { data } = useGetIndicesQuery({...});

data.map((item) => { 
  // check the type of the item using some unique property
  if ('M' in some.scores) { 
    const m = some.scores.M; 
    ...
  } 
});

如果您能够更改 API,我强烈建议在响应中使用某种类型的鉴别器,以便更容易识别响应类型。

© www.soinside.com 2019 - 2024. All rights reserved.