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
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.
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.
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.
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}> = [...];
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 '}, ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With