Angular 2声明对象数组 [英] Angular 2 declaring an array of objects

查看:726
本文介绍了Angular 2声明对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表达式:

public mySentences:Array<string> = [
    {id: 1, text: 'Sentence 1'},
    {id: 2, text: 'Sentence 2'},
    {id: 3, text: 'Sentence 3'},
    {id: 4, text: 'Sentenc4 '},
];

这不起作用,因为我的数组不是string类型,而是包含对象列表.我怎样才能delcare我的数组以包含对象列表?

which is not working because my array is not of type string rather contains a list of objects. How I can delcare my array to contain a list of objects?

*没有新的组件,它声明了一个似乎很浪费的句子类

*without a new component which declaring the a class for sentence which seem a waste

推荐答案

我假设您正在使用打字稿.

I assume you're using typescript.

要格外小心,您可以将type定义为需要与某些接口匹配的对象数组:

To be extra cautious you can define your type as an array of objects that need to match certain interface:

type MyArrayType = Array<{id: number, text: string}>;

const arr: MyArrayType = [
    {id: 1, text: 'Sentence 1'},
    {id: 2, text: 'Sentence 2'},
    {id: 3, text: 'Sentence 3'},
    {id: 4, text: 'Sentenc4 '},
];

或者没有定义自定义类型的简短语法:

Or short syntax without defining a custom type:

const arr: Array<{id: number, text: string}> = [...];

这篇关于Angular 2声明对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆