After reviewing the previous question: Typescript: exclude undefined/null properties from type
In my TypeScript project, I attempted to create an overload for a function called request
, which can optionally accept a payload
. The function is defined by the TEndpointsPayload
interface (shown below) and when a property contains null, it indicates that no payload is required.
Here are the relevant types:
export type TEndpointsPayload = {
getList: null, //No payload required
open: {
name: string
}
close: {
name: string
}
}
export type TEndpointsWithPayload = {
[K in keyof TEndpointsPayload as TEndpointsPayload[K] extends null ? never : K]: TEndpointsPayload[K]; //Contains the 'open' | 'close'
};
export type TEndpointsWithoutPayload = {
[K in keyof TEndpointsPayload as TEndpointsPayload[K] extends null ? K : never]: TEndpointsPayload[K]; //Contains only the 'getList'
};
This is how the function overload is implemented
//This overload signature is not compatible with its implementation signature.ts(2394)
private async request<T extends keyof TEndpointsWithoutPayload>(endpointName: T): Promise<TEndpointsResponse[T]>;
//Code never fall into this implementation
private async request<T extends keyof TEndpointsWithPayload>(endpointName: T, payload: TEndpointsWithPayload[T]): Promise<TEndpointsResponse[T]> { ... }
I am currently facing two issues. Firstly, the first request
function is causing an error:
This overload signature is not compatible with its implementation signature.ts(2394)
The issue is resolved by making the payload
argument optional, but I want the payload to be required or non-existent based on the TEndpointsPayload
.
Secondly, any usage of these methods always falls back to the first request
implementation (i.e., only allowing request('getList')
without a payload).
I have been unable to achieve the desired behavior outlined below:
request('getList')//OK
request('open', {name}) //OK
request('getList', {test}) //ERROR, no payload allowed
request('open') // ERROR, payload required
Any assistance or guidance would be greatly appreciated! Thank you.