Categories
TypeScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *