简体   繁体   English

如何检查是否定义了泛型类型

[英]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.我希望 function 返回 PaginationOptions 类型或 U 类型(如果它已在 function 调用中声明)。 Is there anyway of doing that?反正有这样做吗?

You can use a conditional return type where you check if unkown extends U .您可以使用条件返回类型来检查unkown是否扩展了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.请注意,您需要对返回值进行类型断言,因为 TypeScript 通常无法理解具有通用返回类型的函数的实现。

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 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM