【问题标题】:Using generics in generics in typescript [duplicate]在打字稿的泛型中使用泛型[重复]
【发布时间】:2021-02-25 02:40:54
【问题描述】:

假设我有这样的东西:

type Id<T> = T;
const f = <B>(a: Id<B>, b: B): [Id<B>, B] => [a, b];

但我想扩展 f 以便能够使用其他依赖类型

type List<T> = T[];

我怎样才能实现类似的目标

const f = <A, B>(a: A<B>, b: B): [A<B>, B] => [a, b];
f<Id, number>(1, 2) // evaluates to [1,2]
f<List, number>([1], 2) // evaluates to [[1],2]

没有打字稿抱怨A 不是通用的?还是传递给泛型的类型必须是平面类型?

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    不幸的是,TypeScript 没有直接支持您希望A 成为的那种高级类型 (HKT)。如果不立即指定其类型参数,例如 Id&lt;T&gt; 某些 T,您将无法引用 Id。请参阅microsoft/TypeScript#1213 以获得对更高种类类型的长期开放功能请求。该问题确实列出了可以在 TypeScript 中模拟/模拟 HKT 的一些方法,但我真的不推荐它。

    例如,您可以执行类似这样的操作,通过merging it into an interface declaration 显式注册您关心的每个高级类型:

    type Id<T> = T;
    interface HKTRegistry<T> { Id: Id<T> };
    
    type List<T> = T[];
    interface HKTRegistry<T> { List: List<T> }
    

    然后你可以这样使用它:

    const f = <A extends HKT, B>(a: Specify<A, B>, b: B): [Specify<A, B>, B] => [a, b];
    
    const id = f<"Id", number>(1, 2);
    const hmm = f<"List", number>([1], 2);
    

    HKTSpecify 的定义如下:

    type HKT = keyof HKTRegistry<any>
    type Specify<H extends HKT, T> = HKTRegistry<T>[H];
    

    Playground link to code

    但它很笨重,并且不能捕获 constrained 类型参数之类的东西,而且很难推断这种方式的 HKT。正如我所说,它并不是我真正推荐用于任何生产代码的地方。

    【讨论】:

      猜你喜欢
      • 2015-11-27
      • 1970-01-01
      • 2021-11-26
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 2017-09-16
      • 2018-11-17
      相关资源
      最近更新 更多