HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Safe navigation operator (?.) or (!.) and null property paths

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertynavigationnullandsafepathsoperator

Problem

In Angular 2 templates safe operator ?. works, but not in component.ts using TypeScript 2.0. Also, safe navigation operator (!.) doesn't work.

For example:

This TypeScript

if (a!.b!.c) { }


compiles to this JavaScript

if (a.b.c) { }


But when I run it, I get the follow error:

Cannot read property 'b' of undefined

Is there any alternative to the following?

if (a && a.b && a.b.c) { }

Solution

Since TypeScript 3.7 was released you can use optional chaining now.

Property example:

let x = foo?.bar.baz();


This is equvalent to:

let x = (foo === null || foo === undefined)
  ? undefined
  : foo.bar.baz();


Moreover you can call:

Optional Call

function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}


otherFn will be called only if otherFn won't be equal to null or undefined

Usage optional chaining in IF statement

This:

if (someObj && someObj.someProperty) {
  // ...
}


can be replaced now with this

if (someObj?.someProperty) {
  // ...
}


Ref: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

Code Snippets

let x = foo?.bar.baz();
let x = (foo === null || foo === undefined)
  ? undefined
  : foo.bar.baz();
function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}
if (someObj && someObj.someProperty) {
  // ...
}
if (someObj?.someProperty) {
  // ...
}

Context

Stack Overflow Q#40238144, score: 164

Revisions (0)

No revisions yet.