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.
Add "optional chaining" resolve?
+this.activatedRoute?.snapshot?.paramMap?.get('id'), just suggesting.– Cmte Cardeal
No, keep the same mistake
– Rafael Costa
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.– Cmte Cardeal
or
+this.activatedRoute!.snapshot!.paramMap!.get('id')– Cmte Cardeal
When I do this, it works, but then the following error occurs in this: Forbidden non null assertion (no-non-null-assertion)
– Rafael Costa
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– LeAndrade
This answers your question? How to deal with Undefined (or null) union in Typescript?
– Luiz Felipe