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

How to check if generic type is defined

I have some utils that looks like that :

export const localStorageToPaginationOptions = <T extends LocalStorage, U>({
  searchTerm,
  filters,
  sortBy,
  orderAsc,
  ...props
}: T & U): PaginationOptions | U => ({
    ...props,
    search: searchTerm,
    orderMode: orderAsc ? OrderMode.asc : OrderMode.desc,
    orderBy: sortBy,
    filters,
  });

I would like the function to return either the PaginationOptions type or the U type if it has been declared in the function call. Is there anyway of doing that ?

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 :

You can use a conditional return type where you check if unkown extends U. Note that you are gonna need a type assertion for the return value as TypeScript is generally not able to understand implementations of functions with generic return types.

export const localStorageToPaginationOptions = <T extends LocalStorage, U>({
  searchTerm,
  filters,
  sortBy,
  orderAsc,
  ...props
}: T & U): unknown extends U ? PaginationOptions : U => ({
    /* ... props ... */ 
  } as unknown extends U ? PaginationOptions : U);

This leads to the following behavior when called:

const a = localStorageToPaginationOptions({})
// const a: PaginationOptions

const b = localStorageToPaginationOptions<LocalStorage, { something: "for U" }>({})
// const b: {
//    something: "for U";
// }

Playground

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