Error encountered with Angular version 11.2.6 or Typescript indicating TS2345 issue

Currently, I am stuck on an Angular tutorial that includes some code, but unfortunately, I am encountering an error that I haven't been able to troubleshoot. In all instances within my code where dish or getDish are present, they are stored as strings. Even though the string contains a number, it is consistently treated as a string.

I have attempted to retrace my steps through the tutorial and compared all the instructions with the versions I have uploaded to Github. As I am relatively new to Angular, it is possible that the tutorial could be referring to a different version?

The error message reads:

Error: src/app/dishdetail/dishdetail.component.ts:23:42 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

23     this.dish = this.dishservice.getDish(id);  
                                            ~~

dishdetail.component.ts

import { Component, OnInit } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';

import { Params, ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-dishdetail',
  templateUrl: './dishdetail.component.html',
  styleUrls: ['./dishdetail.component.scss']
})
export class DishdetailComponent implements OnInit {

  dish: Dish;

  constructor(private dishservice: DishService,
    private route: ActivatedRoute,
    private location: Location) { }

  ngOnInit() {
    const id = +this.route.snapshot.params['id'];
    this.dish = this.dishservice.getDish(id);
  }

  goBack(): void {
    this.location.back();
  }

}

dish.service.ts

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable({
  providedIn: 'root'
})
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: string): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}

menu.component.ts

import { Component, OnInit } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';
import { DishService } from '../services/dish.service';


@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

  dishes: Dish[] = DISHES;

  selectedDish: Dish;

  constructor(private dishService: DishService) { }

  ngOnInit() {
    this.dishes = this.dishService.getDishes();
  }

  onSelect(dish: Dish) {
    this.selectedDish = dish;
  }

}

If additional files are required, please let me know and I can provide them.

Answer №1

Erase the + sign in

const id = +this.route.snapshot.params['id'];

to obtain:

const id = this.route.snapshot.params['id'];

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

The headerStyle does not have any impact on the header component in React-Native

Currently diving into React-Native with Typescript and working on a project. Encountered a bug where the header color isn't changing as expected. Any help or insight would be greatly appreciated! -Viggo index.tsx import React, { Component } from & ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

Leverage glob patterns within TypeScript declaration files

Utilizing the file-loader webpack plugin allows for the conversion of media imports into their URLs. For example, in import src from './image.png', the variable src is treated as a string. To inform TypeScript about this behavior, one can create ...

Navigating through React with Typescript often involves managing the process of waiting for an API call to finish

My interface structure is as follows: export interface Chapter{ id: string, code: string } Within a component, I am making an API call in the following manner: componentDidMount() { fetch("https://someapi/getchapter") .then(r ...

Ways to invoke a function from an imported component located in a separate file using React and Typescript

I am currently facing a challenge with connecting a button on my homepage to redirect to another link. I am looking to utilize functions from a different file, specifically a file named SettingsMenu.tsx. The component structure of the SettingsMenu file is ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...

Firestore rule rejecting a request that was meant to be approved

Recently, I came across some TypeScript React code that fetches a firestore collection using react-firebase-hooks. Here's the snippet: const [membersSnapshot, loading, error] = useCollectionData( query( collection(db, USERS_COLLECTION).withConve ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...

Why do selected items in Ionic 3 ion-option not get deselected even after reloading or reinitializing the array

HTML File: <ion-item class="inputpsection" *ngIf="showDeptsec"> <ion-label floating class="fontsize12">Department</ion-label> <ion-select (ionChange)="showDepartmentChosen($event)" multiple="true" formControlName=" ...

What is the best way to pass updates from input model class in a child component to its parent in Angular 13?

What is the best way to propagate changes in the input model class from a child component to its parent in Angular 13? Child Component export class ChildComponent implements OnInit { @Input() mdlInData: any; @Output() mdlOutData = new EventEmitter< ...

Dragging and dropping in Angular does not move to the intended location within a mat dialog

Attempting to manipulate the order of a lengthy list by dragging and dropping items. In a basic component, moving an item is uncomplicated - able to drag it anywhere within the list. While dragging, can scroll through contents beyond visible range and dro ...

Is it possible to convert a type to a JSON file programmatically?

Recently, I have been tasked with implementing configuration files for my system, one for each environment. However, when it came time to use the config, I realized that it was not typed in an easy way. To solve this issue, I created an index file that imp ...

Is there an issue with validation when using looped radio buttons with default values in data-driven forms?

Within my reactive form, I am iterating over some data and attempting to pre-set default values for radio buttons. While the default values are being successfully set, the validation is not functioning as expected. <fieldset *ngIf="question.radioB ...

What is the method for invoking a class method in Typescript from another method within the same class acting as an event handler?

I came across this TypeScript code that I need help with: class MyClass { constructor() { $("#MyButton").on("click", this.MyCallback); this.MyMethod(); } MyCallback = () => { $.ajax("http://MyAjaxUrl") ...

"Error: The React TypeScript variable has been declared but remains

Seeking guidance on ReactTS. I'm puzzled by the undefined value of the variable content. Could someone shed light on why this is happening and how to assign a value to it for passing to <App />? The issue persists in both the index.tsx file and ...

What is the best way to modify the disabled attribute?

After disabling a button using a boolean variable, updating the variable does not remove the disabled attribute. How can I update my code to enable the button when the variable changes? Here is my current code snippet: var isDisabled = true; return ( ...

Creating Dynamic CSS Styling with Vendor Prefixes in Angular 2

I am exploring how to create a component in Angular 2 with two input arguments: colorOne and colorTwo. The goal is to fill a <div> with a gradient of these two colors. If I simply wanted to set the div background color to colorOne, I could achieve t ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

When is the best time in the redux flow to utilize methods for displaying notifications, such as toasts?

As I develop my angular2 app using ngrx/store, I am wondering at which point in the redux lifecycle I should trigger methods to display notifications (toasts). My initial thought is to handle this in side effects (utilizing ngrx/effects). @Effect({ dispa ...