Home > database >  Can I pass an infinite number of arguments to a generic type?
Can I pass an infinite number of arguments to a generic type?

Time:02-09

I'm trying to pass a few arguments, but I get an error from linter: TS2314: Generic type 'FruitKit ' requires 1 type argument(s).

I tried to use something by type ...args, but it also didn't work.

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
    }
};

CodePudding user response:

You can only pass a single type argument to a type that expects only a single type parameter. What you in this case depends on what you want, whether you want FruitKit<Apple, Banana> to mean that each property is both an Apple and a Banana, or that each property is either an Apple or a Banana. From your example usage, I suspect you want either/or, which is the union type Apple | Banana:

interface MyCustomFruitKit extends FruitKit<Apple | Banana> {}

Playground link

(If you wanted them to be both, it would be &, an intersection, rather than |, and your objects in the usage example would need all four properties [red and yellow and ripe and rotten].)


Side note: I'd avoid having a type and a constant with the same name (FruitKit). Although the names live in different namespaces, it's still confusing to the programmer reading the code.

  •  Tags:  
  • Related