How does this strange JavaScript code work? Mystery colon

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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;

Method 2

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

Method 3

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply