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.
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;
It is basic typescript declaration and initilaization. refer to this link for more details
https://www.typescriptlang.org/docs/handbook/basic-types.html
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