Typescript: Define array containing unknown amount of different custom interfaces

Viewed 30

I am having a really hard time understanding how i define arrays containing different amount of different types/interfaces.

Lets say i have the three interfaces with some properties (i use these to initialize my objects let int_a: IntA = { ... }):

interface IntA { ... some properties ... };
interface IntB { ... some properties ... };
interface IntC { ... some properties ... };

I want to store an unknown amount of these in an array/map (my_array = [int_a, int_b, int_a, int_c, int_b, ... ]):

interface Container {
    my_array: Array<MyType>
}

What is the type MyType suppose to be equal to? Is it [intA|IntB|IntC][] or IntA[]|IntB[]|IntC[] or [IntA[]|IntB[]|IntC[]][]? or something completely else? Here i ask a specific question, but i would love and appreciate alot an elaborate answer around defining array containing custom types/interfaces.

1 Answers

You should use an array of the union type, not a union of the array types:

interface Container {
    my_array: (IntA | IntB | IntC)[];
}
let int_A: IntA;
let int_B: IntB;
let int_C: IntC;
myContainer: Container = { my_array: [int_A, int_B, int_A, int_C, int_C, int_B] } // Works

The other way would error, because the array would have to be all IntA or all IntB or all IntC:

interface Container {
    my_array: IntA[] | IntB[] | IntC[];
}
let int_A: IntA;
let int_B: IntB;
let int_C: IntC;
myContainer: Container = { my_array: [int_A, int_B, int_A, int_C, int_C, int_B] } // Does not work
// only these work:
containerA: Container = { my_array: [int_A, int_A, int_A] }
containerB: Container = { my_array: [int_B, int_B, int_B] }
containerC: Container = { my_array: [int_C, int_C, int_C] }
Related