The left-hand operator in Typescript is not valid

I am a beginner in typescript and I have been following a tutorial called Tour of Heroes on Angular's website. In the final chapter of the tutorial, when I tried to use HTTP with the provided code, everything seemed to run fine but I encountered an error from the typescript compiler.

https://i.sstatic.net/iqye0.png

The issue is that because of this error, I have to refresh the browser as BrowserSync is not syncing properly due to the error. Can anyone help me with this?

Below is the code:

Hero.service.ts

import { HEROES }from './mock.heroes';
import { Hero } from './hero';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HeroService {
    url: string;
    constructor(private http: Http){
        this.url = "http://jsonplaceholder.typicode.com/users";
        this.http = http;
    }
    getHeros(): Promise<Hero[]> {
        if(!HEROES || HEROES.length == 0) {
            return this.http.get(this.url)
                .toPromise()
                .then(response => {
                    HEROES = response.json();
                });
        } else {
            let promise: Promise<Hero[]> = new Promise<Hero[]>(function(resolve, reject){
                resolve(HEROES);
            });
            return promise;
        }
    }
}

mock.heroes.ts

import { Hero } from './hero';
export var HEROES: Hero[];

Answer №1

Instead of assigning Json to the HERO array, make sure to cast the result properly.

One suggestion is to loop through the response data and construct the HERO array using Object.assign if there are any functions in the HERO class.

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

Dealing with TypeScript issues while implementing Multer in an Express application

import multer, { FileFilterCallback } from "multer"; import sharp from "sharp"; import { NextFunction, Request, Response } from "express"; const multerStorage = multer.memoryStorage(); const multerFilter = ( req: Request, ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

Encountered error code 3228369023 while trying to establish a connection to a SQL Server database using Node.js with MSSQL

Currently in the process of setting up an API for a SQL Server Express database, my plan is to utilize mssql in Node.js with express to handle requests and communicate with the database. Despite trying several methods to establish a connection between my n ...

NetBeans is unable to analyze javascript files that are considered "large" (over 350 KB)

I have a significant JavaScript file (approximately 6 MB) that includes library API and documentation as shown below: /** * Function doc */ library.class.func=function(something){}; /** * Function 2 doc */ library.class.func2=function(something){}; ...

Tips for utilizing a vue.js nested for loop with two arrays using v-for

The issue has been resolved, and both my parent view and child component code are now correct and functioning properly I am using Vue.js with the goal of iterating similarly to a nested for loop to display a matrix table. Initially, I tried to achieve thi ...

Challenge with Typescript Interfaces

Can someone help me with understanding interfaces in typescript? I am currently facing an issue with the code. The error message says: Type 'Response' is missing the following properties from type 'myObj': userId, title, id I believe ...

Construct object in JavaScript recursively

My current project involves creating a file structure index using nodeJS. I am utilizing the fs.readir function to iterate through files and it is working smoothly. However, I am facing an issue when it comes to descending into the directory structure and ...

Manipulate database variables using Javascript

As a beginner in JavaScript, I am seeking assistance with some tasks. I have to save a simple number as a JavaScript variable into a database and display the current value on two websites (with PHP used to retrieve it on the second site). This is my curre ...

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

How come my effort to evade quotation marks in JSON isn't successful?

When trying to parse a JSON-string using the JQuery.parseJSON function, I encountered an error message that read: Uncaught SyntaxError: Unexpected token R. This was unusual as the only uppercase 'R' in my JSON-formatted string appeared right afte ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

The content in tinymce cannot be edited or removed

Is there a method to prevent certain content within the tinyMCE Editor from being edited or removed? While I know that adding a class "mceNonEditable" can make a div non-editable, it can still be deleted. Is there a way to make it unremovable as well? ...

Display Quantity of Current Website Visitors

Similar Question: how to track website visitors using java script or php I am looking to retrieve the current number of viewers on a webpage that has an embedded stream. Is there a method to accomplish this utilizing PHP and AJAX, in order to display ...

How can you initialize Boostrap components or Materialize css in Angular 5 without using any external libraries?

I am a beginner exploring the world of Typescript and Angular. I am curious about how to initialize Bootstrap elements in an Angular-friendly manner without using the ngx-Bootstrap wrapper. For instance, if I wish to initiate a Bootstrap carousel. As per ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

Combine the values of identical keys from multiple objects in an array by utilizing the forEach method in JavaScript

I am currently working on refining a shopping basket function with Vue JS. One of the key features I need to implement is a subtotal calculation that multiplies the price and quantity values for each item and then combines them to create an overall subtota ...

Unable to activate Vue 13 keyCode in a text field using jQuery with Laravel Dusk Testing

I've been grappling with this issue for a few days now. I'm trying to create a Laravel Dusk test that incorporates the Vue.js framework. There's a method that should be triggered when the user hits the ENTER key. I recently discovered that ...

The Angular tag <mat-expansion-panel-header> fails to load

Every time I incorporate the mat-expansion-panel-header tag in my HTML, an error pops up in the console. Referencing the basic expansion panel example from here. ERROR TypeError: Cannot read property 'pipe' of undefined at new MatExpansionPanel ...