what `?` means before some object attribute? and why my ts file doesn´t accept it?

Viewed 209

i´ve always use this kind of behavior show down here in angular *ngIf directive when i have an object that could be undefined or other than the required object

<div *ngIf="object?.foo">
  ...
</div>

i know that this works, but don´t know why...

But when i tried to use it on an if in my TypeScript file like following angular throw me two diferent errors TS1005, TS1109, alternating one to other, on each line that i try to use this behavior.

if(object?.foo){} // error TS1109
if(object?.foo){} // error TS1005
if(object?.foo){} // error TS1109
if(object?.foo){} // error TS1005

i'm using Angular 7.3.9 for this project

2 Answers

The reason it works in your template is because angular will evaluate it to the following expression:

<div *ngIf="object && object.foo">

Which will prevent the error of calling the property on the object if the object is null.

Documentation link: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

It is not working in the typescript part of your component because it is not supported by typescript.

The only use of ? for variables in typescript is to specify that a parameter to a method is optional:

function myFunc(mandatoryParam: any, optionalParam?: any) {
    ...
}

myFunc('hello'); // Will work
myFunc('hello', 'world'); // Will work too

As mentioned in the comments to this answer, TypeScript will add the support for the angular template syntax in the 3.7 version: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

Related