Understanding the contrast between ":" and "=" in Angular 2

When working with Angular 2, I've observed that there are different ways to declare variables - using =, :, and public.

For example:

  public heroes = HEROES;
  title = "Tour of Heroes";
  selectedHero: Hero;

What exactly is the difference between them? Is it only about initialization?

Answer №1

In javascript, there is no required type checking, allowing you to assign variables with different types like someVar="hello" and then someVar=true, which is acceptable in javascript. TypeScript, on the other hand, provides type checking capabilities and other features for javascript, regardless of initialization.

  • = sets the value of the variable
  • : sets the type of the variable

For example:

public heroes = HEROES;  // assigns value of HEROES to heroes, heroes now has an inferred type same as the type of HEROES
title = "Tour of Heroes"; // normal assignment with inferred type of 'string'
selectedHero: Hero; // just declares selectedHero with the type 'Hero'

You can define both a value and type simultaneously:

title:string = "some text"; // this means, title is of type string and has the value "some text"

If later you try title=true, the compiler will warn you about assigning a boolean value to a string variable.

Extra You can also set multiple types instead of just one:

title:string|boolean=true; // title is of type either string or boolean
title:"text1"|"text2"|"text3"; // (v1.8 and after) title is of type string and can have only one of the values: "text1","text2" or "text3". in other words enum type 
title:any; // title is of any type.

On function declaration:

someFunction(name:string):boolean{
    // the parameter 'name' is expected to be of type string in the body of this function

    return true; // the return type of the function is expected to be boolean
}

Lambda Expression:

someFunction = (name:string):boolean => {
    // the variable name is expected to be of type string in the body of this function
    return true;
}

For more information, check out:
Typescript specs for Types
Typescript Type System

Answer №2

: Specifies the variable type without setting an initial value.

= Sets an initial value for a variable while also defining its type.

When "public" is used, it declares a variable as accessible from outside the class, contrary to being private.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic routerLink value in Angular 8 for items within an ngFor loop

I am currently attempting to route a dynamic value from the NgFor using [routerLink]. <li class="list-group-item d-flex justify-content-between align-items-center" *ngFor="let factors of factorsList"> <span>{{factors | ...

The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this: import { NgModule } from '@angular/core'; import { ...

Can we automate the process of generating Typescript classes from VB.net server-side classes?

Currently, I am developing a web application project where the server language is VB.net and the frontend is built using Angular (typescript). One issue I have been facing is that every time a class model is created in VB.net, the same class needs to be ma ...

How can you efficiently enable Angular 4 routing on a production server?

It took me a dedicated 6 days to transition an HTML5-only app into an Angular 4 routing application, all in the hopes of enhancing its SEO capabilities. However, upon deployment, I discovered that direct URLs were resulting in frustrating 404 pages. For e ...

Guide to implementing a specified directive value across various tags in Angular Material

As I delve into learning Angular and Material, I have come across a challenge in my project. I noticed that I need to create forms with a consistent appearance. Take for example the registration form's template snippet below: <mat-card> <h2 ...

Ways to evaluate two objects and update the key identifier?

Compare the keys in the headerObject with the keys in dataObj and create a new object using the labels from headerObject. const headerObject = [{ label: 'Code', field_key: 'code' }, { label: 'Worked Accounts&apos ...

Creating a personalized URL when utilizing the router-outlet with a specific name

Can someone assist in removing the sidebar:cart-page from here? https://i.sstatic.net/AOb4S.jpg I am looking to create a common inner cart component that can be searched based on tags without including sidebar:cart-page. https://i.sstatic.net/8rpvB.png ...

Learn how to retrieve data from a parent component in Angular 8 by leveraging the window.opener property in a child window

On my Angular application, I have 2 separate pages - page1 and page2. Page1 has a button that, when clicked, opens page2. Since they are different components, I need to use window.opener to access data from page1 in page2 by calling window.opener.page1Func ...

The ng generate component command is only failing in one specific module due to an error that says "Cannot read property '0' of null"

Attempting to create a fresh component within one of my modules. After navigating to [project]/src/app, I type in the following command: ng g c admin/list where admin represents an existing module and list is the desired name for the new component. The ...

Is there a way to display a variety of images on separate divs using *ngFor or another method?

I have created a custom gallery and now I would like to apply titration on the wrapper in order to display a different image on each div. Currently, my code is repeating a single image throughout the entire gallery. HTML <div class="wrapper" ...

Comparing type inference with explicit type declaration in TypeScript

In my coding experience, I've noticed that some developers declare variables with an explicit type even when the inferred type is clear: For example: loading: boolean = false, name: string = "John", or count: number = 0, and so on. I have observed t ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

The conditional type in TypeScript is malfunctioning

Upon finishing an article discussing conditional types in TypeScript located at: I have attempted to implement a conditional type in the following function: function convertToIsoString<T extends number|undefined>( timestamp:T ): T extends number ...

Having trouble building my Angular 2 app with Angular-cli beta 14, despite it working perfectly fine with systemjs beforeEach

I have been using VSCode on Windows 10 to work on an app developed in Angular 2 final version, which runs smoothly with systemjs. Recently, I upgraded to angular-cli beta 14 webpack version and followed the steps outlined in the upgrade document here. How ...

A more efficient approach to specifying types for the 'navigation' object in React Native's Stack Navigator

Struggling with modularizing prop types in React Navigation, particularly when using TypeScript. The Typescript section of the React Navigation documentation suggests defining types for each screen props in this manner: //types.ts export type RootStackPara ...

An Uncaught Error has occurred: The module titled "functions" has not been loaded within the current context _. To resolve this issue, please make sure to use

I've been grappling with setting up TypeScript in my ASP.NET Core project without much success. Initially, I managed to implement a basic functionality where an alert pops up when the page loads successfully. My next challenge was to manually conver ...

send image back to Angular component from server response

I'm extremely close to achieving my goal. The server is successfully returning the image and sending it in the response. Now, the challenge lies in getting my angular component to properly display it. Let me share what I have done so far: Firstly, h ...

How can TypeScript be used to remap an interface for a single element when destructuring an object?

In Typescript 3.4, when destructuring an object, you can define the exact response type like this: interface IResponse { loading: boolean; data: any; error: string; } interface IObject { ... } const {loading, data, error}:{data: IObject} = ...

Including a hyperlink in a table using Angular 8

I have a table with multiple columns, one of which is the "documents" column that contains downloadable files. How can I make just the document name clickable as a link? HTML <p-table #dt3 [columns]="colsPermessi" [value]="permessi" [paginator]="true" ...

Component view displaying undefined when fetching data with Angular5 HttpClient

I'm having trouble accessing a JSON data from an API and displaying it in my component's HTML using ngFor. When I log the data returned from the API inside the http.get function, it looks fine. But for some reason, it's not working when I tr ...