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

标签 typescript

谁能给我一些建议。我这里有一组对象:

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' },
];

我想做的是找到如何在 Typescript 中定义它。

最佳答案

不太清楚你的意思:

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

但一种选择是引入接口(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);

查一下in action here

关于typescript - 如何使用 Typescript 定义对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31937865/

相关文章:

angular - 如何减轻标签点击?

reactjs - 如何推断从模式创建的对象的类型?

javascript - 使用 PM2 运行 Typescript 应用程序

使用 routerLink 的 Angular 2 单元测试组件

typescript - 更新到 27 后,Angular jest 无法理解导入路径

typescript - 从联合类型创建类似记录的类型

typescript - 在 Typescript 中使用 '--strictFunctionTypes' 有什么好处?

typescript - "Cannot read property toLowerCase of undefined"在 ionic 构建 ios 上

javascript - 类方法在哪里被调用?

typescript 仅从重载中选择特定方法(要传递给 Parameters<T>)