Reputation:
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
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
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
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
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