如何使用Typescript编写具有约束扩展iterable的泛型类型

如何使用Typescript编写具有约束扩展iterable的泛型类型,typescript,typescript-generics,Typescript,Typescript Generics,我试着写这种类型: type Pagination<I extends Iterable> = Readonly<{ seek: number; limit: number; total: number; items: I; }>; 虽然这也可以工作,但类型签名现在变成了分页,无法进一步限制应使用哪种类型的iterable。您可以使用iterable本身的泛型参数,而不是item类型,使用T extends Iterable您可以将其设置为类型Pagin

我试着写这种类型:

type Pagination<I extends Iterable> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: I;
}>;

虽然这也可以工作,但类型签名现在变成了分页,无法进一步限制应使用哪种类型的iterable。

您可以使用iterable本身的泛型参数,而不是item类型,使用
T extends Iterable

您可以将其设置为
类型Pagination=Readonly
@TitianCernicova Dragomir这就是答案!请提交此问题的答案。
current
是否像一个具体化类型?在中,该值不存在,因此它只是用于帮助参数化其他需要内部项类型的函数吗?@cmcdragokai不确定我是否理解您的评论。当前项的类型没有相对于
T
定义,因此如果
T
Iterable
(这将是由于其他约束),我们将得到Iterable的
项。这确实可以帮助参数化其他需要项类型的函数
Pagination<Map<number, any>>
type Pagination<I> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: Iterable<I>;
}>;
type Pagination<I extends Iterable<any>> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: I;
}>;
type Pagination<I extends Iterable<any>> = Readonly<{
  seek: number;
  limit: number;
  total: number;
  items: I;
  current: I extends Iterable<infer Item> ? Item: never
}>;

declare let map: Pagination<Map<string, number>>
map.current // [string, number]

declare let arr: Pagination<string[]>
arr.current // string