I am in the process of gradually converting a large SvelteKit application to TypeScript, focusing on refining the API layer. Currently, I am grappling with a function that has two generics:
// Function that either performs a POST or a PUT
export function save<T, U>(basePath: string, data: U, token?: string): Promise<T> {
if (data.id) {
return put<T, U>(`${basePath}/${data.id}`, data, token);
} else {
return post<T, U>(basePath, data, token);
}
}
The main concept behind this code is to ensure both the input data and output result are typed (taking inspiration from ). The `data` parameter is of generic type `U`, but there is a need to verify whether it contains an `id` property or not. How can this validation be implemented? Currently, I am encountering the error "Property 'id' does not exist on type 'U'", which is understandable, but I am uncertain about the correct solution.