Angular 2 declaring an array of objects

前端 未结 7 2099
-上瘾入骨i
-上瘾入骨i 2020-12-13 08:48

I have the following expression:

public mySentences:Array = [
    {id: 1, text: \'Sentence 1\'},
    {id: 2, text: \'Sentence 2\'},
    {id: 3,         


        
7条回答
  •  误落风尘
    2020-12-13 09:32

    I assume you're using typescript.

    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}> = [...];
    

提交回复
热议问题