Reputation: 5540
There is a variable v
in my program, and I want to check if its property p
contains a sub string sub
. I could write a code like follows:
if (v.p.indexOf('sub') !== -1) {
// do something here
}
However, I have some doubts when seeing this code:
v
is never declaredp
does not exist in v
?v.p
is null
or undefined
?v.p
is not a stringI want all the above cases not to raise errors in my code, and only do something here
when v.p
exists and contains a string that contains sub
.
Does anyone know how to write this code correctly?
Upvotes: 0
Views: 369
Reputation: 418
With TS you can use "Optional chaining"
For example
let x = foo?.bar.baz();
this is a way of saying that when foo is defined, foo.bar.baz() will be computed; but when foo is null or undefined, stop what we’re doing and just return undefined.”
More plainly, that code snippet is the same as writing the following.
let x = (foo === null || foo === undefined) ?
undefined :
foo.bar.baz();
See more https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html Optional chaining
Upvotes: 2