【问题标题】:Infer nested generic types in typescript?在打字稿中推断嵌套的泛型类型?
【发布时间】:2020-12-17 05:52:44
【问题描述】:

假设我有

interface Animal {}

interface Group<A extends Animal> {}

我想在 Group 上创建一个通用接口

interface AnimalGroupProps<G extends Group<A>, A extends Animal> {
  withGroup: () => G
  // We want to be able to reference A in the interface, for use like this:
  withLeader: () => A
}

我希望动物组道具在组类型上是通用的。但是A extends Animal 似乎是多余的。我想说的是:

interface AnimalGroupProps<G extends Group<A>>

然后让 TypeScript 弄清楚。但是 TypeScript 想要声明 A,所以我 必须使用之前sn-p的模式。

class Wolf implements Animal {}

class WolfPack implements Group<Wolf> {}

function AnimalPlanetWolves ({withGroup, withLeader}: AnimalGroupProps<WolfPack, Wolf>) {}
//                          This is the really annoying part --------------------^^^^

AnimalGroupProps 的所有用户都必须指定两个通用参数,即使 尽管其中之一是完全多余的。在我的实际代码库中,那将是 很多冗余。


在上面的示例中,WolfPack 不是泛型类型。如果有一个 你想传递给 AnimalGroupProps 的泛型类型?其实还 更糟糕的是:

interface Flock<A extends Animal> extends Group<A> {}

class Geese implements Animal {}

function AnimalPlanetBirds ({withGroup, withLeader}: AnimalGroupProps<Flock<Geese>, Geese>) {}

【问题讨论】:

  • Group&lt;A&gt; 有没有涉及A 的成员?它应该。
  • @AluanHaddad 在实际用例中确实如此。对于 Group 示例,您可以有一个 addMember: (A) => void
  • 所以您可以使用interface AnimalGroupProps&lt;G extends Group&lt;Animal&gt;&gt; { withLeader: () =&gt; Parameters&lt;G['addMember']&gt;[0] },但 ccarton 的回答在这种情况下提供了更好的方法。

标签: typescript generics


【解决方案1】:

是的,Typescript 具有推断嵌套类型的语法。

type AnimalForGroup<G> = G extends Group<infer A> ? A : never

你仍然需要在模板参数中列出A,但你可以给它一个默认值:

interface AnimalGroupProps<G extends Group<A>, A extends Animal = AnimalForGroup<G>> 

【讨论】:

  • 谢谢!我遇到了 infer,但错误地认为它不适用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2021-12-20
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多