gpt4 book ai didi

typescript - 在 typescript 中推断嵌套的泛型类型?

转载 作者:行者123 更新时间:2023-12-05 00:55:42 24 4
gpt4 key购买 nike

假设我有

interface Animal {}

interface Group<A extends Animal> {}

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

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
}

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

interface AnimalGroupProps<G extends Group<A>>

然后让 TypeScript 弄清楚。但是 TypeScript 想要声明 A,所以我必须使用前一个片段的模式。

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>) {}

最佳答案

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

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

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

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

关于typescript - 在 typescript 中推断嵌套的泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63631364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com