简体   繁体   English

推断打字稿中的嵌套泛型类型?

[英]Infer nested generic types in typescript?

Suppose I have假设我有

interface Animal {}

interface Group<A extends Animal> {}

And I want to make an interface generic over Group我想在 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
}

I want animal group props to be generic over the group type.我希望动物组道具在组类型上是通用的。 But the A extends Animal seems redundant.但是 A 扩展 Animal 似乎是多余的。 I'd like to be able to say:我希望能够说:

interface AnimalGroupProps<G extends Group<A>>

And have TypeScript figure it out.并让 TypeScript 弄清楚。 But TypeScript wants A to be declared, so I have to use the previous snippet's pattern.但是 TypeScript 想要声明 A,所以我必须使用前面代码片段的模式。

class Wolf implements Animal {}

class WolfPack implements Group<Wolf> {}

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

All users of AnimalGroupProps have to specify both generic parameters, even though one of them is entirely redundant. AnimalGroupProps 的所有用户都必须指定两个通用参数,即使其中之一是完全多余的。 In my actual codebase, that would be a lot of redundancy.在我的实际代码库中,这将是很多冗余。


In the above example WolfPack was not a generic type.在上面的例子中 WolfPack 不是一个泛型类型。 What if there was a generic type that you wanted to pass to AnimalGroupProps?如果您想传递给 AnimalGroupProps 的泛型类型怎么办? It's actually even worse:实际上更糟糕的是:

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

class Geese implements Animal {}

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

Yes, Typescript has a syntax to infer nested types.是的,Typescript 具有推断嵌套类型的语法。

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

You still need to list A in the template arguments but you can give it a default value:你仍然需要在模板参数中列出A但你可以给它一个默认值:

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

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

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