简体   繁体   English

如何使用Typescript定义对象数组?

[英]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. 我想做的是找到如何在Typescript中定义它。

Not fully sure what do you mean by: 不完全确定您的意思是:

What I would like to do is to find how I can define this in Typescript. 我想做的是找到如何在Typescript中定义它。

But one option is to introduce the interface and declare variable as array of such objects: 但一种选择是引入interface并将变量声明为此类对象的数组:

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 在这里检查

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. 然后按照OP的问题填充数组。

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. 在此示例中,对象的'key'属性是字符串数组。

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

or 要么

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

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>();
}
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"
  }]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM