0

I want to allow an arrays of objects of any shape, as long as they have id: number present.

So whether it is an array of OrderModel or UserModel (both of which have id: number), how can I define such an array?

export interface Item { id: number; // whatever else, doesn't matter }

a person
  • 1,518
  • 3
  • 17
  • 26

1 Answers1

2

Considering the fact that arrays are covariant, just define Item as:

interface Item {
  id: number;
}

Then let say you have the following types:

interface OrderModel {
  id: number;
  type: "order";
  // other props
}

interface UserModel {
  id: number;
  type: "user";
  // other props
}

The following will be allowed:

declare const os: Array<OrderModel>;
declare const us: Array<UserModel>;

declare function doStuff(xs: Array<Item>): unknown;

doStuff(os);
doStuff(us);

Playground

Andrea Simone Costa
  • 1,164
  • 6
  • 16