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 而是包含对象列表。我怎样才能让我的数组包含一个对象列表?

*没有一个新的组件来声明一个看起来很浪费的句子的类

原文由 TheUnreal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

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

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

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

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

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

原文由 martin 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

OR

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

原文由 nick 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进