gummiost gummiost - 1 month ago 11
TypeScript Question

How does this strange JavaScript code work? Mystery colon

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.

Answer

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. Type declarations can be found in strong-typed programming languages; for example, the equivalent in C# would be:

Hero[] HEROES;