typescript - TypeScript 中具有泛型类型参数的泛型类型的替代方案

标签 typescript generics typescript-generics

假设我有两种类型的泛型函数,它们仅在返回类型上有所不同。一个具有返回类型 T,另一个具有 T[]:

type F1 = <T>(t: T) => T
type F2 = <T>(t: T) => T[]

我想知道如何将这两种类型合并为一种通用类型。我想象的方式是让新的泛型类型接受另一个泛型类型作为参数(如 C++ 的 template template parameters ):

// Caution, Fantasy-TypeScript ahead!

// Accepts generic type R as parameter
// to transform return type of generic function
type F<R> = <T>(t: T) => R<T>

// define F1 and F2 in terms of F
type Id<T> = T
type F1 = F<Id>
type F2 = F<Array>

但是,尚不支持泛型泛型参数(2021 年 3 月)。请参阅TypeScript Issue和一个related SO question了解更多信息。

TypeScript 中的替代方案是什么?

最佳答案

一个简单的方法是使用 Conditional Types :

type F<R> = <T>(t: T) => R extends void[] ? T[] : T

type F1 = F<void>   // <T>(t: T) => T
type F2 = F<void[]> // <T>(t: T) => T[]

使用 Indexed Access Types 可以实现更灵活的实现:

type R<T> = { Id: T, Array: T[] }
type F<K extends keyof R<any>> = <T>(t: T) => R<T>[K]

type F1 = F<'Id'>    // <T>(t: T) => T
type F2 = F<'Array'> // <T>(t: T) => T[]

参见my answer to a similar question有关此技术的更复杂的示例。

关于typescript - TypeScript 中具有泛型类型参数的泛型类型的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66616254/

相关文章:

angular - window.scroll 不适用于 Angular 11 和 Material

java - 声明泛型类型时的编译器警告

Typescript - 为什么没有相应地强制实现接口(interface)

typescript - 我可以将泛型类型作为类型参数传递吗?

Typescript:提供对未从模块导出的变量的类型安全访问的通用函数

Angular 2 : When onChange is triggered, 如何检索选择的值和选择元素的 id?

angular - Angular 2 中 Zone.js 的用途是什么

node.js - Angular 6 ssr页面负载太大

java - 陷入泛型困境

java - 在 Java 泛型中,List<? super String> 是什么意思?