Anne Anne - 1 month ago 4
TypeScript Question

How can I define an array of objects using Typescript?

Can someone give me some advice. I have an array of objects here:

contentOrderBy = [
{ id: 0, name: 'CId', key: 'contentId' },
{ id: 1, name: 'Modified By', key: 'modifiedBy' },
{ id: 2, name: 'Modified Date', key: 'modified' },
{ id: 3, name: 'Status', key: 'contentStatusId' },
];


What I would like to do is to find how I can define this in Typescript.

Answer Source

Not fully sure what do you mean by:

What I would like to do is to find how I can define this in Typescript.

But one option is to introduce the interface and declare variable as array of such objects:

interface IMyEntity {
    id: number;
    name: string;
    key: string;    
}

var contentOrderBy = [
    { id: 0, name: 'CId', key: 'contentId' },
    { id: 1, name: 'Modified By', key: 'modifiedBy' },
    { id: 2, name: 'Modified Date', key: 'modified' },
    { id: 3, name: 'Status', key: 'contentStatusId' },
];

// finally here we have declaration of the array
// which contains the items of specified type/interface
// and we can later work with them "fully-typed"
var myContent : IMyEntity[] = contentOrderBy;

alert(myContent[0].name);

Check it in action here