Reputation: 783
I'm following the official Angular 2 tutorial and then I saw this piece of code:
const HEROES: Hero[] = ...
I don't understand how the colon can be after HEROES, I can't find any documentation on this colon usage in JavaScript and TypeScript. I thought the colon were only used in object "key: value" and ternary operators.
export class Hero {
id: number;
name: string;
}
const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
Can you help me understand this colon syntax?
The other questions answer does not explain about typescript and that it is a special syntax.
Upvotes: 9
Views: 4046
Reputation: 31934
This is TypeScript code, and this is how you declare (annotate) the type of a variable in TypeScript. The declaration means that the type of HEROES
should be Hero[]
, an array of Hero
objects.
var HEROES: Hero[];
The TypeScript compiler will use this information to prevent incorrect assignments to this variable -- for example, you cannot assign a number
to HEROES
(not just because the latter is a constant in your code, but because it would be a type-error).
Type declarations can be found in strong-typed programming languages; for example, an equivalent in C# would be:
Hero[] HEROES;
Upvotes: 8
Reputation: 1894
const HEROES: Hero[] = [
...
];
The :
is a way to specify the type of a variable in TypeScript language, here HEROES is an Array of Hero instance.
This notation is called type annotation, refer this.
Upvotes: 1
Reputation: 1426
It is basic typescript declaration and initilaization. refer to this link for more details
https://www.typescriptlang.org/docs/handbook/basic-types.html
Upvotes: 1