How to define an interface for an array of objects with TypeScript?

Sometimes, we want to define an interface for an array of objects with TypeScript.

In this article, we’ll look at how to define an interface for an array of objects with TypeScript.

How to define an interface for an array of objects with TypeScript?

To define an interface for an array of objects with TypeScript, we can define the interface for each object.

For instance, we write

interface EnumServiceItem {
  id: number;
  label: string;
  key: any;
}

const result: EnumServiceItem[] = [
  { id: 0, label: "CId", key: "contentId" },
  { id: 1, label: "Modified By", key: "modifiedBy" },
  { id: 2, label: "Modified Date", key: "modified" },
];

to create the EnumServiceItem interface that has the id, label and key properties.

Then we set the result variable to the EnumServiceItem[] type.

And then we assign an array of objects that matches the structure described in EnumServiceItem to result result.

The properties listed and their types must all match to prevent any TypeScript compiler errors.

Conclusion

To define an interface for an array of objects with TypeScript, we can define the interface for each object.