How to define an array of objects using Typescript?

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

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 find how I can define this in Typescript.

+6
source share
4 answers

Not quite sure what you mean by this:

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

But one of the options is to enter interface and declare the variable as an 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); 

Mark in action here

+7
source

To declare an array, the following two syntaxes are valid: if you are looking for an option that avoids using an interface:

 contentOrderBy: { id: number, name: string, key: string }[]; 

or

 contentOrderBy: Array<{ id: number, name: string, key: string }>; 

Then fill the array as in the OP question.

Since I found this question when looking for the right way to define an array inside an object, I will also add this example. In this example, the "key" property of an object is an array of strings.

 contentOrderBy: { id: number, name: string, key: string[] }[]; 

or

 contentOrderBy: Array<{ id: number, name: string, key: Array<string> }>; 
+2
source

You can try any of them. They do not give me errors.

 //Declare with default value private _possessions: Array<Thing> = new Array<Thing>(); 

or

 //declare private _possessions: Array<Thing>; constructor(){ //assign this._possessions = new Array<Thing>(); } 
0
source
 var storesArray : Store[] = [ { app_category : "app_cat", app_id : "11", id : "12", name : "g1", target_audience: "tar_aud", type: "intune" }, { app_category : "app_cat2", app_id : "112", id : "122", name : "g12", target_audience: "tar_aud2", type: "intune2" }] 
0
source

All Articles