SoftTimur
SoftTimur

Reputation: 5540

Safe way to check if a property of an object contains a substring

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:

  1. What if v is never declared
  2. What if the property p does not exist in v?
  3. What if v.p is null or undefined?
  4. What if v.p is not a string

I 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

Answers (1)

Isa
Isa

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

Related Questions