Reputation: 449
In the Angular official tutorial they have an example of a simple class (https://angular.io/tutorial/toh-pt1) and they use the class like an object, which I don't understand.
class Hero{
id: number;
name: string
and it's used like this...
const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
];
and this is used as a list in the HTML. (https://angular.io/tutorial/toh-pt2)
Being new to Typescript, I simply don't understand how this is done. In Python for ex. the only way to use a Class is to instantiate it. I know objects can be created and used like this in Javascript, but to my knowledge not using the class keyword.
I've googled this, watched vids on Typescript, and cannot find anyone else doing something similar. If someone could point me to documentation I would appreciate it greatly! Or, just a simple explanation with ex.
Upvotes: 0
Views: 88
Reputation: 28128
I found this very confusing as well. Once you use the class
keyword, I think it makes more sense to use new
to create instances as well.
It's not just 'syntactic sugar', it's also about defining a workflow.
If you prefer the Javascript syntax for working with objects, Typescript provides a way to define a Type for an object:
type Hero = { id: number, name: string }
const Heroes: Hero[] = [
{id:3, name:"henk"}
]
Upvotes: 1
Reputation: 13148
This is more or less just basic JavaScript. {}
instantiates an object in JavaScript, and { id: 5 }
instantiates an object and gives it an 'id'
field with the value 5
.
Additionally, JavaScript has "duck typing", so to match "type" with a class you just need to share the same members. There's no actual "type". TypeScript introduces type checking, but the underlying object still has no intrinsic type.
Also TypeScript has lots of type inference, so it can see that the members match and will infer that they should be of type Hero
.
Upvotes: 2
Reputation: 163
Let's have a look at the documentation.
Define a HEROES constant as an array of ten heroes.
Do you understand what is going on here? We take an array of ids and names and we are assigning that to an array of hero elements. A single element version would be like the following:
const HERO: Hero = { id:21, name: 'myName'};
It's very struct-like in nature, but testing here shows you its just turns into var HERO = { id: 50, name: 'test' };
. There are other ways to get immutability for an object but syntactically they are a nightmare, but that's neither here nor there. This was merely a way to shorthand the instantiation into one "line" (i.e. before a semicolon).
Upvotes: 0