Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 491
TheUnreal Avatar asked Sep 09 '16 08:09

TheUnreal


People also ask

How to declare an array of objects Angular?

Alias Object Type Array in Angular# AngularJs type Fruit = Array<{ id: number; name: string }>; In the next example, we create a Fruit alias of array type and initialize Array with object values. Now, we display the object on the front end file. We can declare an array of objects utilizing the interface type.

How to declare array of objects in Angular TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error.

How do you define a string array in TypeScript?

To define an array of strings, set the type of the array to string[] , e.g. const arr: string[] = [] . If you try to add a value of any other type to the array, the type checker would show an error.


2 Answers

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}> = [...]; 
like image 99
martin Avatar answered Oct 03 '22 02:10

martin


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

Or rather,

export interface type{     id:number;     text:string; }  public mySentences:type[] = [     {id: 1, text: 'Sentence 1'},     {id: 2, text: 'Sentence 2'},     {id: 3, text: 'Sentence 3'},     {id: 4, text: 'Sentenc4 '}, ]; 
like image 22
Nikhil Shah Avatar answered Oct 03 '22 00:10

Nikhil Shah