Typescript error: Object is possibly 'null'

Asked

Viewed 2,175 times

0

I have the following component in Angular:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
    
@Component({
  templateUrl: './course-info.component.html'
})
    
export class CourseInfoComponent implements OnInit {
  courseId = 0;
  constructor(private activatedRoute: ActivatedRoute) {  }
  ngOnInit(): void {
    this.courseId = +this.activatedRoute.snapshot.paramMap.get('id');
}

The TS is giving me the following error in the excerpt this.activatedRoute.snapshot.paramMap.get('id'):

TS2531: Object is possibly 'null'.

Does anyone know how I can treat it?

  • Add "optional chaining" resolve? +this.activatedRoute?.snapshot?.paramMap?.get('id') , just suggesting.

  • No, keep the same mistake

  • Then try to add the ! in the end, +this.activatedRoute.snapshot.paramMap.get('id')!, When Voce is sure this object exists, Voce states this to the TS and then he "trusts" Voce. Try this.

  • or +this.activatedRoute!.snapshot!.paramMap!.get('id')

  • When I do this, it works, but then the following error occurs in this: Forbidden non null assertion (no-non-null-assertion)

  • 1

    I don’t know if I understand the problem, but it wouldn’t just be using the operator OR (||) after the expression?! Getting like this: this.courseId = +this.activatedRoute.snapshot.paramMap.get('id') || 123

Show 2 more comments

2 answers

1


The problem is that you may happen to try to convert a null for Number with the unary operator +, and Typescript interprets this as a possible logic error.

If it’s "all right" convert null for 0, this can be solved by using the constructor Number(variável) for the conversion of the value, because the constructor Number() accepts any value (any). Otherwise, do a treatment for the value null.

const teste = null;
console.log(+teste); // Aqui aparece o erro

console.log(Number(teste)); // Aqui não há erro

// Mas repare que o comportamento em JS de ambos os casos é o mesmo

See on Playground


This error happens in the unary operator + because in the entire call below, the only possible return null is at the end of the current, in .get().

+this.activatedRoute.snapshot.paramMap.get('id')

So make use of the optional chaining, as suggested in the comments, it would be somewhat unnecessary and would not solve the problem, since neither activatedRoute, snapshot or paramMap can return values null. This can be observed through the documentation of the Angular:

interface ActivatedRoute {
  snapshot: ActivatedRouteSnapshot
  // ...
}

interface ActivatedRouteSnapshot {
  paramMap: ParamMap
  // ...
}

interface ParamMap {
  get(name: string): string | null  // Aqui pode retornar null
  // ...
}

Typescript also points to the use of non null assertion (the use of !) as an error because you would simply be ignoring a case (the return null) which may or may not result in unexpected behaviour in its application.

-3

Perfect what the Cardinal Cmte said! Add a "!" after that part of the code that will perfectly pass --> +this.activatedRoute.snapshot.paramMap.get('id')!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.