In my React/Typescript app, I currently have the following code snippet -
export type GetPricingParams = {
search_id: number,
promo_code?: string,
};
export type GetPricingData = {
amount: number,
currency: string,
search_id: number,
applied_promocode?: {
type: 'AMOUNT' | 'PERCENT',
discount: number,
},
};
export const getPricing = api.post<GetPricingData, GetPricingParams>('/api/v1/pricing');
The api.post
method serves as a wrapper for the axios post method -
post: <D = unknown, P = undefined>(uri: string): ReturnType<D, P> => (params, config) =>
{
return axios.post(uri, params, config).then(r => Promise.resolve(r.data));
},
I am keen on making the applied_promocode
a required parameter in the GetPricingData
if the promo_code
parameter is specified in the GetPricingParams
.
I attempted the following approach, however, it was unsuccessful -
export type GetPricingParams = {
search_id: number,
promo_code?: string,
};
export type GetPricingDataCommon = {
amount: number,
currency: string,
search_id: number,
};
export type GetPricingDataWithPromocode = GetPricingDataCommon & {
applied_promocode: {
type: 'AMOUNT' | 'PERCENT',
discount: number,
},
};
export const getPricing = <P extends GetPricingParams>(params: P) =>
{
return api.post<
P extends {promo_code: string} ? GetPricingDataWithPromocode : GetPricingData,
GetPricingParams
>('/api/v1/pricing')(params);
}