How can I define a TypeScript interface for an array of objects?
Hi,
You can define the Interface as an Array of Objects. Instead of defining the interface as an array type, define it as a shape for individual objects and use that interface to type the array:
interface IenumServiceGetOrderBy {
id: number;
label: string;
key: string | string[]; // Adjusted to reflect the possible types of 'key'
}
const getOrderBy = (entity: string): IenumServiceGetOrderBy[] => {
let result: IenumServiceGetOrderBy[];
switch (entity) {
case "content":
result = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
break;
default:
result = [];
break;
}
return result;
};
If you want to keep the interface as an array type, you can use type assertions to assure TypeScript that the array elements conform to the interface:
interface IenumServiceGetOrderBy {
id: number;
label: string;
key: string | string[];
}
const getOrderBy = (entity: string): IenumServiceGetOrderBy[] => {
let result: IenumServiceGetOrderBy[];
switch (entity) {
case "content":
result = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
] as IenumServiceGetOrderBy[];
break;
default:
result = [];
break;
}
return result;
};
You can define the interface for individual objects and then use it in a generic array type:
interface IenumServiceGetOrderBy {
id: number;
label: string;
key: string | string[];
}
const getOrderBy = (entity: string): Array<IenumServiceGetOrderBy> => {
let result: Array<IenumServiceGetOrderBy>;
switch (entity) {
case "content":
result = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
break;
default:
result = [];
break;
}
return result;
};