I am a beginner; so don't be bothered by the basics of my question. When learning typescript, when assigning the type to an array of objects, I did it in the following way:
let titulos:object[]=[
{titulo: 'el resplandor'},
{titulo: 'soy yo'}
]
It works well. But when I want to do something like that inside an angular component
export class TitulosComponent implements OnInit {
titulos:object[];
constructor() {
this.titulos= [
{titulo: "hola"},
{titulo: "chau"},
{titulo: "anda rápido"},
{titulo: "anda volando"}
]
}
ngOnInit(): void {
}
}
And it throws me an error when I want to access the property of the object through an *ngFor directive:
<ul>
<li *ngFor="let titulo of titulos">{{titulo.titulo}}</li>
</ul>
Tells me
error TS2339: Property 'title' does not exist on type 'object'.
But if I don't assign the type to the property, it doesn't give any error. Or be it like this:
export class TitulosComponent implements OnInit {
titulos;
constructor() {
this.titulos= [
{titulo: "hola"},
{titulo: "chau"},
{titulo: "anda rápido'"},
{titulo: "anda volando'"}
]
}
ngOnInit(): void {
}
}
I am self taught and can't figure out why this is happening. Can someone explain it to me? Thank you very much.
Typescript is a weird mix between javascript and a strongly typed language.
In a strongly typed language the Object is (usually) a class from which all other objects descend, it is the parent class of everything.
But this class has no attributes and that's why it throws you an error. What you are trying to do is convert an Object to something else it is not, this can be done in Javascript but not in Typescript
Why does it work if you remove the type?
That is, if you leave it like this:
Because this is the same as placing:
The 'any' type is Typescript's response to be compatible with javascript. An any can be anything and it's the same as Object in javascript and maybe that's where the confusion comes from.
Finally, the normal thing in a strongly typed language is to create a Class or an Interface that defines your objects