Typescript - How to to create array with multiple types

Viewed 1148

I have one common interface and two interfaces "Person" and "Employee" that extend the first one:

    export interface Common {
        id: number,
        name: string
      }

      export interface Person extends Common {
        age: number;
      }

      export interface Employee extends Common {
        role: string;
      }

I need to have an array mixed with these interfaces, for example this:

listOfPeople: Person[] | Employee[] = [{id: 1, name: 'George', age: 4}, {id: 2, name: 'Micheal', role: 'software developer'}];

but in this way I got an error. What's the correct way for obtaining the result that I desire?

2 Answers

You can combine the types and declare them as the type for the listOfPeople using the union type.

So this would work I guess

listOfPeople: (Person|Employee)[]

Because listOfPeople is an array that can contain any of these. You must let TS know that it is an array.

const listOfPeople: (Person|Employee)[] = [{id: 1, name: 'George', age: 4}, {id: 2, name: 'Micheal', role: 'software developer'}];

Another (maybe clearer) way of writing this type would be:

listOfPeople: Array<Person | Employee>;
Related