我可以向泛型类型传递无限数量的参数吗



我试图传递一些参数,但从linter得到一个错误:TS2314:泛型类型"FruitKit"需要1个类型参数。

我试着按类型使用一些东西。。。args,但它也不起作用。

interface Apple {
red: number;
yellow: number;
}
interface Banana {
ripe: number;
rotten: number;
}
interface FruitKit<T> {
fruits: T
}
interface MyCustomFruitKit extends FruitKit<Apple, Banana> {}
const FruitKit: MyCustomFruitKit = {
fruits: {
red: 1,
yellow: 2
}
};

只能将单个类型参数传递给只需要单个类型参数的类型。在这种情况下,您需要什么取决于您想要什么,是希望FruitKit<Apple, Banana>意味着每个属性都是AppleBanana,还是每个属性都AppleBanana。根据您的示例用法,我怀疑您想要非此即彼,即联合类型Apple | Banana:

interface MyCustomFruitKit extends FruitKit<Apple | Banana> {}

游乐场链接

(如果您希望它们都是,那么它将是&,一个交集,而不是|,并且您在使用示例中的对象将需要所有四个属性[redyellow以及riperotten]。(


旁注:我会避免使用具有相同名称的类型和常量(FruitKit(。尽管这些名称位于不同的名称空间中,但对于阅读代码的程序员来说,这仍然是令人困惑的。

最新更新