Imagine a more streamlined design:
type BaseResponse<T> = {
success: boolean;
data?: T;
}
Consider the following function, which merges multiple BaseResponse
objects into one:
zip<T1, T2>(response1: BaseResponse<T1>, response2: BaseResponse<T2>): BaseResponse<T1 & T2> {
let success = true;
let data: Partial<T1 & T2> = {};
if (!response1.success) success = false;
else data = {...data, ...response1.data};
if (!response2.success) success = false;
else data = {...data, ...response2.data};
return {
success,
data: success ? data as any : undefined,
};
}
This approach is effective for handling two arguments. Is there a way to generalize it for an arbitrary number of arguments T1, T2, ..., TN?
In terms of implementation, utilizing a for loop for iterating through arguments could simplify the process. However, I am interested in how the function signature would need to be adapted to accommodate this flexibility.