Home > Back-end >  Vue / Typescript Generics for interface
Vue / Typescript Generics for interface

Time:10-13

What is the correct syntax for allowing anything extending a base type in the following scenario?

interface SomeBase {}
interface A extends SomeBase {}
interface B extends SomeBase {}

interface Foo {
 bar: // Can be an array of A or B
}

Is it just bar: SomeBase[] or is there something like bar: <? extends SomeBase>

I don't want to do bar: A[] | B[] as there may be a large amount of interfaces and I'd like to avoid explicitly writing them out.

I don't see any documentation offhand for defining it as a variable inside an interface.

CodePudding user response:

bar: SomeBase[] would allow an array of mixed types. If you want a single one, it should be generic.

interface SomeBase {}
interface A extends SomeBase {}
interface B extends SomeBase {}

type Foo <T extends SomeBase> = {
 bar: T[];
}
  • Related