我是打字稿新手。
我有查询端点,这个查询根据不同的参数给我不同的响应,如下所示:
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
?
我应该为此创建不同的端点吗?
不确定我是否理解正确,但是在使用查询时需要转换类型,或者应用某种保护。仅从查询来看,并不清楚是否返回
IGetTradeVolume[]
或IGetRecent[]
,因此 typescript 假设它是两者之一,这意味着您只能访问共享属性。选项 1:投射响应
选项 2:使用防护装置
如果您能够更改 API,我建议您按照您的考虑使用两个不同的端点。另一种可能性是在响应中使用某种类型的鉴别器,以便更容易区分响应类型(请参阅此示例)。这取决于您的 API,哪一个更适合。