【发布时间】:2021-06-13 16:04:47
【问题描述】:
我希望我的标题是明确的,但我对 TS 比较陌生,而且我正在努力处理联合类型。
我正在尝试创建一个通用的callApi 函数,它允许可选的paging 和filters 查询参数。但是,我想让过滤器选项强类型,例如,当调用/api/people/时,我只想允许PeopleFilterQueryParams。
这是我到现在为止的想法,但是,它允许 id 和 after 过滤器查询参数 - 当它应该只允许两者之一时。
export type BookingQueryParams = {
before?: string;
after?: string;
}
export type PersonQueryParams = {
id?: number;
}
export type FilterQueryParams = BookingQueryParams | PersonQueryParams;
export interface PaginationQueryParams {
page?: number;
size?: number;
}
export interface ApiRequestParams {
filters?: FilterQueryParams;
paging?: PaginationQueryParams;
}
export const callApi = (url: string, params?: ApiRequestParams) => {
return ``;
}
callApi('/people', {
filters: {
id: 123,
after: '',
}
})
我在这里有一个 TS 游乐场链接来展示我的问题: TS playground
任何帮助将不胜感激!
【问题讨论】:
标签: typescript