Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript : Colon vs Equal To ( Angular Tutorial )

I am learning Angular4 and going through the tutorial examples.

https://angular.io/docs/ts/latest/tutorial/toh-pt1.html

I have the below code in the tutorial.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>{{title}}</h1><h2>{{hero.name}} details!</h2>`
})
export class AppComponent { 
    title = 'Tour of Heroes'; // *1
      hero: Hero = {
      id: 1,
      name: 'Windstorm'
    };
  }

export class Hero {
  id: number; // *2
  name: string;
}

In the code 2 classes are defined, AppComponent and Hero. I am not able to understand why for member declaration of a class, AppComponent follows the style property = value while class Hero uses style property : value

If I change the class AppComponent to the below, the code doesn't work as expected.

export class AppComponent { 
    title : 'Tour of Heroes', 
      hero: Hero : {
      id: 1,
      name: 'Windstorm'
    };
  }

I would like to know whats the difference between using : and using = and when what should be used ?

like image 807
geeky_monster Avatar asked Apr 12 '17 11:04

geeky_monster


People also ask

What is colon used for in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.

What is ?: In TypeScript?

Using ?: with undefined as type definition While there are no errors with this interface definition, it is inferred the property value could undefined without explicitly defining the property type as undefined . In case the middleName property doesn't get a value, by default, its value will be undefined .


1 Answers

Look again at the AppComponent:

export class AppComponent { 
  title = 'Tour of Heroes';
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };
}

The first field definition:

title = 'Tour of Heroes';

is assigning a string value. Because that value is a string, TS can infer the type. The line is equivalent to:

title: string = 'Tour of Heroes';

The second field definition

hero: Hero = {
  id: 1,
  name: 'Windstorm'
};

is assigning an object, which could be any type. So here, to get the most out of TS, we should be specific about the kind of thing it will be. It could also be written:

hero: { id: number, name: string } = {...};

In the Hero class, you're only setting types, no default values. The pattern is actually the same in both:

name[: type][ = value];

It's probably worth having a look in the TS handbook for more information about types and class definitions.

like image 64
jonrsharpe Avatar answered Nov 14 '22 05:11

jonrsharpe