【发布时间】: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<A>有没有涉及A的成员?它应该。 -
@AluanHaddad 在实际用例中确实如此。对于 Group 示例,您可以有一个 addMember: (A) => void
-
所以您可以使用
interface AnimalGroupProps<G extends Group<Animal>> { withLeader: () => Parameters<G['addMember']>[0] },但 ccarton 的回答在这种情况下提供了更好的方法。
标签: typescript generics