user1464139
user1464139

Reputation:

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.

Upvotes: 10

Views: 37186

Answers (4)

Julian Fraser
Julian Fraser

Reputation: 1428

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

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

or

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

Then populate the array as in the OP's question.

Since I found this question while searching for the correct way to define an array inside the object I will add that example also. In this example the 'key' property of the object is an array of strings.

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

or

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

Upvotes: 6

Umair Akbar
Umair Akbar

Reputation: 588

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"
  }]

Upvotes: 0

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123851

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

Upvotes: 15

Rahul
Rahul

Reputation: 726

You could try either of these. They are not giving 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>();
}

Upvotes: 0

Related Questions