I am slowly migrating a sizable SvelteKit application to TypeScript, and I am current working on the API layer. Here I have a function with two generics:
// Either does 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 idea being that both the data and the result will be typed (inspiration from https://eckertalex.dev/blog/typescript-fetch-wrapper). So data is a generic U type, but I still want to check if it has an id property or not. How can this be done? Currently I get the error "Property ‘id’ does not exist on type ‘U’" which makes perfect sense but I am not sure how to solve it.
>Solution :
Add a constraint to U.
export function saveApi<T, U extends { id?: string }>(fetch: Fetch, basePath: string, data: U, token?: string): Promise<T> {
if (data.id) {
return putApi<T, U>(fetch, `${basePath}/${data.id}`, data, token);
} else {
return postApi<T, U>(fetch, basePath, data, token);
}
}