The type 'string | null' cannot be assigned to the type 'string | undefined'. Specifically, the type 'null' cannot be assigned to the type 'string | undefined'

When I define a property as id!:string; or id:string=''; and try to assign the value of params, an error occurs

(property) MoreParametersComponent.id: string ts(2322)Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-more-parameters',
  templateUrl: './more-parameters.component.html',
  styleUrls: ['./more-parameters.component.css']
})
export class MoreParametersComponent implements OnInit {
  id!: string; // or id:string='';
  id2:number=0;
  constructor(private activatedRoute:ActivatedRoute) { }

  ngOnInit(): void {
    this.activatedRoute.paramMap.subscribe(params=>{
      this.id=params.get('id'); // produces the error above here
      this.id2=parseInt(params.get('id2'));//error
    });
  }

}

How can I resolve this issue?

Remaining Code:

app.component.html

<a routerLink=""> Home </a><br>
<a routerLink="one-parameter,'p01'"> One-Parameter </a><br>
<a routerLink="more-parameter,{id:'p02',id2:123}"> More-Parameter </a> 
<br><br>
<router-outlet></router-outlet>
<br><br>

Route.config.ts

import { Routes } from '@angular/router'
import { HomeComponent } from './home/home.component';
import { MoreParametersComponent } from './more-parameters/more-parameters.component';
import { OneParamterComponent } from './one-paramter/one-paramter.component';


export const mainroute:Routes=[
    {path:'',component:HomeComponent},
    {path:'one-parameter',component:OneParamterComponent},
    {path:'more-parameter',component:MoreParametersComponent}
];

Answer №1

The result of using ParamMap.get is string | null but it doesn't match the type of your id.

If needed, you can convert the return value of ParamMap.get to a string by doing params.get('id') as string

Alternatively, you have the option to subscribe to params instead, which gives you an object with property type "any" and allows you to access the id parameter using an object key like this: params.id. More details here: https://angular.io/api/router/Params

Answer №2

To provide assurance to the compiler that the id will never be empty, consider appending an exclamation mark '!' at the end.

this.id=params.get('id')!;
this.id2=parseInt(params.get('id2')!);

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

Troubleshooting error messages with Angular 2 HttpClient response payload

Currently, I am implementing the latest version (4.3) of HttpClient in angular to handle data POST requests to my backend server: this.httpClient.post<View>(`/path`, data).subscribe( (view: View) => console.log("Success"), (error: HttpErrorRe ...

Switching an Enum from one type to another in JavaScript

UPDATE After reading a comment, I realized that Enum is not native to JavaScript but is actually part of TypeScript. I decided to keep the original title unchanged to help others who may also make the same mistake as me. I am faced with a scenario where ...

Encountering the NullInjectorError: No provider for Injector! error repeatedly while attempting to interact with a store

I've been working on a web app that incorporates a store by following this tutorial: . However, I keep encountering the following error: main.ts:13 NullInjectorError: StaticInjectorError(AppModule)[InjectionToken @ngrx/store Initial Reducers -> In ...

Utilizing browser history navigation features in Angular 6: A comprehensive guide

I am looking to take charge of my Angular 6 web application. Is there a way to send an alert to users if they refresh the screen? If so, how can I achieve this? ...

Enhance your images with the Tiptap extension for customizable captions

click here for image description I am looking to include an image along with an editable caption using the tiptap extension Check out this link for more information I found a great example with ProseMirror, but I'm wondering if it's possible ...

Issue with starting Angular2 beta 15 using npm command

I am encountering a problem when trying to launch the quick start application for Angular2. node -v 5.10.1 npm -v 3.8.6 My operating system is EL CAPTAIN on MAC OS X. This is my tsconfig.json file: { "compilerOptions": { "target": "es5", "mo ...

Encountering problem with React Typescript fetching data from Spring Data REST API: the error message "Property '_embedded' does not exist" is being displayed

I am currently working on a React application that utilizes Typescript to fetch data from a Spring Data REST API (JPA repositories). When I make a specific request like "GET http://localhost:8080/notifications/1" with an ID, my JSON response does not pose ...

My Angular2 pipe is not working as expected

I have developed a custom pipe to search through a table based on ID. Below is the example JSON data that I am utilizing to populate the tables: [ { "id": "59247cd5a05cfa4966af706d", "lease": { "client": { "client_id": 1, ...

Working with Angular: Accessing SCSS variables from style.scss using JavaScript inside a component

I am working on an Angular 9 application that utilizes Angular Material and has two themes, namely dark and light. These themes are defined in the style.scss file as follows: $rasd-dark-text-color: mat-palette($mat-grey, 300); $rasd-light-text-color: mat-p ...

Getting a precise item in JSON with varied key signatures

Given the following JSON data: var responses = {customer : {results: 2938; id: 9283}, bredesh : {results: 2938; id: 248} }; I am trying to use an if statement in my HTML template : <div ng-if="response.(customer and bredesh and any new element (Is ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

What allows mapped types to yield primitive outputs when using {[P in keyof T]}?

Check out this innovative mapped type example that utilizes the power of keyof: type Identity<T> = { [P in keyof T]: T[P]; }; Have you ever wondered why Identity<number> results in the primitive number type, rather than an object type? Is th ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

Efficiently managing the completion of multiple observables from dynamic components in a smart component using RxJS

Welcome, I am working on a project where I need to generate a PDF export by clicking on a button within the page. The page contains a dynamic dashboard with multiple charts that are generated dynamically. My goal is to have each dynamic component create a ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

Navigating to the root of a child component in Angular2 routing can be achieved by using the Router

In the App.ts file, I have configured the following router: @RouteConfig([ {path: '/', redirectTo: ['Login']}, {path: '/login', name: 'Login', component: LoginComponent}, {path: '/dashboard', n ...

Angular 6 Time Discrepancy

I am trying to display real-time time difference on the UI that updates every second. Here is what I have attempted: component.ts import { Component, OnInit } from '@angular/core'; import 'rxjs/add/observable/of'; import 'rxjs/a ...

How can you connect a collection to a user profile?

Currently, I am developing a MEAN application using Angular 2+. I am looking to implement a separate data storage for each user. At the moment, all data can be accessed by anyone, but I want it so that only the user who enters the details can view them. Es ...

Ensuring the Existence of Variables Based on Parameterized Type in TypeScript Return Type Declaration

Within my TypeScript class called Design, there is a method named checkFetched. This method's purpose is to verify the existence of a property of type DesignData within an instance of the class, based on a parameterized type called Filename. Here is a ...