Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: have a generic parameter but still check if it has a certain property

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading