! 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 ofawithnullandundefinedexcluded
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 (nullorundefined), the expression short-circuits with a return value ofundefined. When used with function calls, it returnsundefinedif 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! 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 ofawithnullandundefinedexcluded
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 (nullorundefined), the expression short-circuits with a return value ofundefined. When used with function calls, it returnsundefinedif 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
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
Suggestion: "safe navigation operator", i.e. x?.y
angular - Is there any Alternate of Safe Navigation Operator for typescript file for versions
Alternate syntax so I can have both a safe navigation and a monad unwrapping operator? - Programming Language Design and Implementation Stack Exchange
apex - Safe Navigation Operator (?.) and integer comparisons - Salesforce Stack Exchange
! 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 ofawithnullandundefinedexcluded
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 (nullorundefined), the expression short-circuits with a return value ofundefined. When used with function calls, it returnsundefinedif 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 OverflowIf 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?
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
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);
}
}
}
Ruby uses the &. token for safe navigation, which can safely coexist with a ? for monads.
foo&.bar # Safe navigation a la Ruby
foo?.bar # Monadic unwrap a la Rust
If you don't like the asymmetry between ? for monad unwrapping and ?? for null coalescing, I'm quite fond of Perl's // for null coalescing. It looks like || (which is similar) but is clearly a different operator. Only downside is it won't work if you're using C-style comments as well.
Asterisk
If you're not already using it and it works with your current syntax, you could use *. for monad unwrapping.
Some(k)*.property = k.property
None(k)*.property = return None