Home > Mobile >  How to check if generic type is defined
How to check if generic type is defined

Time:11-16

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 ?

CodePudding user response:

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

  • Related