TheUnreal TheUnreal - 2 months ago 149
TypeScript Question

Angular 2 declaring an array of objects

I have the following expression:

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


which does not working because my array is not of type
string
, it 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

Answer

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}>;

var 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:

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