Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 397
gummiost Avatar asked Oct 31 '16 12:10

gummiost


2 Answers

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;
like image 197
John Weisz Avatar answered Oct 20 '22 06:10

John Weisz


It is basic typescript declaration and initilaization. refer to this link for more details

https://www.typescriptlang.org/docs/handbook/basic-types.html

like image 39
Narendra CM Avatar answered Oct 20 '22 07:10

Narendra CM