! is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a is not null or undefined.

the operation a! produces a value of the type of a with null and undefined excluded


Optional chaining finally made it to typescript (3.7)

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Syntax:

obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls

Pay attention:

Optional chaining is not valid on the left-hand side of an assignment

const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
Answer from Aleksey L. on Stack Overflow
Top answer
1 of 7
247

! is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a is not null or undefined.

the operation a! produces a value of the type of a with null and undefined excluded


Optional chaining finally made it to typescript (3.7)

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Syntax:

obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls

Pay attention:

Optional chaining is not valid on the left-hand side of an assignment

const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
2 of 7
164

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

🌐
GitHub
github.com › microsoft › TypeScript › issues › 16
Suggestion: "safe navigation operator", i.e. x?.y · Issue #16 · microsoft/TypeScript
July 15, 2014 - Current Status The TC39 proposal is now at stage 3 (🎉🎉🎉🎉🎉) Implementation is in progress You can expect this feature in TypeScript 3.7 We'll update here when it's available in a nightly bui...
Published   Jul 15, 2014

! is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a is not null or undefined.

the operation a! produces a value of the type of a with null and undefined excluded


Optional chaining finally made it to typescript (3.7)

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Syntax:

obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls

Pay attention:

Optional chaining is not valid on the left-hand side of an assignment

const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
Answer from Aleksey L. on Stack Overflow
🌐
Reddit
reddit.com › r/typescript › is there a safe navigation operator for string indexes?
r/typescript on Reddit: Is there a safe navigation operator for string indexes?
November 2, 2022 -

If I try to look up a string index on a nullable object like obj['index'] I get an Object is possibly 'null' error. I know I can do obj && obj['index'] but this gets tiresome especially if you are following multiple levels deep.

obj?['index'] thinks I am trying to do a ternary operator. Is there some sort of way to sugar syntax this?

🌐
Wikipedia
en.wikipedia.org › wiki › Safe_navigation_operator
Safe navigation operator - Wikipedia
1 month ago - In programming languages where ... the safe navigation operator stops the evaluation of a method/field chain and returns null as the value of the chain expression. It was first used by Groovy 1.0 in 2007 and is currently supported in languages such as C#, Swift, TypeScript, Ruby, Kotlin, ...
🌐
DEV Community
dev.to › pssingh21 › safe-navigation-operator-bang-bang-bang-192j
Safe Navigation Operator? Bang! Bang Bang!! - DEV Community
March 12, 2021 - const foo = a?.b //accessing object property const foo = a?.[expr] //accessing through dynamic expression const foo = arr?.[index] //accessing array index const foo = bar?.(args) //conditional function call · Warning: This operator is not valid on the left-hand-side of an assignment operator. ... Note: ?. acts differently than && operator, since the && operator acts on falsy values(including 0, NaN, "", false), but ?. acts on nullish values (null and undefined). Warning: !. is not the same as ?. . The ! postfix expression is valid in TypeScript >= v2.0.
🌐
Beyondjava
beyondjava.net › elvis-operator-aka-safe-navigation-javascript-typescript
Elvis Operator (aka Safe Navigation) in JavaScript and TypeScript
So it checks every access of an attribute or a method of the son attribute. If you forget to add the null, TypeScript faithfully reminds you. The internet has countless descriptions how to write your own safe navigation: Just write a get function and pass the path as string to it.
🌐
Medium
medium.com › @zayani.zied › safe-navigation-operator-optional-chaining-js-and-angular-d253431a2625
Safe Navigation Operator-Optional Chaining (JS and Angular) | by Zied ZAYANI | Medium
February 20, 2023 - Of course, in an Angular application, we can use the safe navigation operator with TypeScript, and we have the ability to use it with template expressions to handle null or undefined values.
Find elsewhere
🌐
Peeyush Singh's Blog
peeyushmansingh.com › safe-navigation-operator-bang-bang-bang
Safe Navigation Operator? Bang! Bang Bang!!
May 25, 2023 - const foo = a?.b //accessing object property const foo = a?.[expr] //accessing through dynamic expression const foo = arr?.[index] //accessing array index const foo = bar?.(args) //conditional function call · Warning: This operator is not valid on the left-hand-side of an assignment operator. ... Note: ?. acts differently than && operator, since the && operator acts on falsy values(including 0, NaN, "", false), but ?. acts on nullish values (null and undefined). Warning: !. is not the same as ?. . The ! postfix expression is valid in TypeScript >= v2.0.
🌐
GitHub
github.com › angular › angular › issues › 13254
Safe navigation does not guard array access · Issue #13254 · angular/angular
August 18, 2016 - Using an array index after a safe navigation, e.g. {{click?.pixel[0]}}, crashes with a Cannot read property '0' of null when the guarded variable is null/undefined. ... The safe operator should short-circuit the entire expression after the first null value, as it does when using property access, e.g.
Published   Dec 05, 2016
🌐
Coderwall
coderwall.com › p › ohcuda › avoid-the-safe-navigation-operator-in-angular
Avoid the Safe Navigation Operator in Angular (Example)
August 16, 2018 - Since an instance of ElvisTest is passed to the component as an Input, it could possibly remain undefined. As such, we could use the Elivs operator to prevent UI errors:
🌐
Howjavascriptworks
howjavascriptworks.com › home › demystifying the safe navigation operator in angular
Safe Navigation Operator Angular: Learn More
November 2, 2023 - ... This ensures that even if ‘user’ or ‘address’ is undefined, your application won’t throw errors. Angular didn’t stop at objects. The Safe Navigation Operator is equally efficient with arrays...
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-3-7.html
TypeScript: Documentation - TypeScript 3.7
Because interfaces (and other object types) introduce a level of indirection and their full structure doesn’t need to be eagerly built out, TypeScript has no problem working with this structure. But workaround of introducing the interface wasn’t intuitive for users. And in principle there really wasn’t anything wrong with the original version of ValueOrArray that used Array directly.
🌐
Medium
medium.com › inside-rimeto › optional-chaining-in-typescript-622c3121f99b
Optional Chaining in TypeScript. Traversing tree-like structures safely… | by Neville Bowers | Inside Rimeto | Medium
December 4, 2019 - Also note the use of T[number]: this notation conveniently extracts the element type U when T is defined as Array<U>. Finally, for primitive types, we simply apply the IDataAccessor<T> interface as no further traversal should be attempted. No good solution exists yet in TypeScript for safely traversing tree-like structures.
🌐
ConcretePage
concretepage.com › angular-2 › angular-2-pipe-operator-and-safe-navigation-operator-example
Angular Pipe Operator (|) and Safe Navigation Operator (?.) - ConcretePage.com
For safer side we can use safe navigation operator to access property from object and hence it will not throw exception for the scenario that object is null or undefined. If we have an object person with the properties name then using safe navigation operator we will access object property as follows. person?.name Now find the typescript file and its HTML template used in our example.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
You can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name: ... This is particularly useful for arrays, since array indices must be accessed with square brackets.
Top answer
1 of 2
1

This feature, called "optional chaining" in MDN and other ECMAScript documentation, was moved to Stage 4 (ready for inclusion) in December 2019 and is published as part of ES2020. As of October 2021, according to caniuse.com, browser support is currently at 90.86% globally.

As described, and as discussed in its issue Microsoft/TypeScript#16, Typescript support for optional chaining was released on 5 November 2019—nearly two years ago at the time of this answer. Compilation solutions also exist in Webpack 5 or Babel's env for ES2020. As such, for most developers, it makes more sense to adopt modern versions of TypeScript tooling than to use an alternative implementation.

If you are strictly unable to use modern tooling, you'll need a helper method; as a language feature, optional chaining cannot be directly polyfilled. Compatible tested alternatives exist in a number of common libraries:

  • Lodash's _.get
  • Underscore's _.get
  • Closure's goog.object.getValueByKeys
2 of 2
-1

I made this function which can be used as alternate of safe navigation operator for typescript versions <3.7

/*
  This function is to validate if Object is accessible or not as well as returns its value if it is accessible.
  it will return false if Object is not accessible (if value is null or undefined)
  If Object is accessible then it will return its value.

  Example: if I want to check that is "obj.key1.key2" is accessible and I want to put check on its value.
  if (isAccessible(obj,["key1","key2"]) == some_value){
    ...do something...
  }

  no need to check for null and undefined for each key.

  NOTE: this function is alternate of "SAFE NAVIGATOR OPERATOR (?)" of typescript which is not supported in versions <3.7
*/

isAccessible(data, keys, start=0) {
  if (start == 0 && (data == null || data == undefined)) {
    console.warn("data",data);
    return data;
  } else {
    if (data[keys[start]] == null || data[keys[start]] == undefined) {
      console.warn("Object valid till", keys.slice(0,start),keys[start],"undefined");
      return data[keys[start]];
    } else {
      if (start + 1 >= keys.length) {
        // console.log("output",data[keys[start]]);
        return data[keys[start]];
      }
      return this.isAccessible(data[keys[start]], keys, start + 1);
    }
  }
}