I have a specific object with the following structure:
{
first: (state: S, payload: boolean) => { payload: boolean, type: string },
second: (state: S) => { payload: undefined, type: string },
}
My goal is to manipulate this object by removing the state
property. This modification results in the following shape:
{
first: (payload: boolean) => { payload: boolean, type: string },
second: () => { payload: undefined, type: string },
}
The output object is defined as follows:
{ [K in keyof T]: { (payload: Parameters<T[K]>[1]): { payload: Parameters<T[K]>[1]; type: K; }; name: K; } }
In this context, Parameters<T[K]>[1]
can potentially hold the value undefined
, such as in the case of second()
.
Although the implementation is mostly successful and correctly infers function names, parameters, and return types, an issue arises when dealing with scenarios where payload
may be undefined. For instance:
first(true); // executes without errors
first('true'); // results in failure due to type mismatch
second(undefined) // no issues are encountered
second(); // triggers an error
The corresponding error message reads as:
(property) second: (payload: undefined) => {
payload: undefined;
type: "second";
}
Expected 1 arguments, but got 0. [ts(2554)]
Hence, the main question revolves around how to make the parameter optional only when no payload
is provided. Adding
(payload?: Parameters<T[K]>[1])
as part of the return type renders all functions inclusive, while using (payload: Parameters<T[K]>[1] | undefined)
does not produce the desired outcome.