0

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?

5
  • You can use lodash _.get function. Or use try...catch Commented Jun 11, 2020 at 9:39
  • Thank you... But I prefer raw typescript or javascript code... Commented Jun 11, 2020 at 9:40
  • 1
    In TS you can use v?.p?.indexOf... Commented Jun 11, 2020 at 9:40
  • I'm writing TypeScript, if you are sure about v?.p?.indexOf, please post an answer... Commented Jun 11, 2020 at 9:41
  • typescriptlang.org/docs/handbook/release-notes/… Optional chaining Commented Jun 11, 2020 at 9:42

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

foo?.bar.baz() will return error TS2304: Cannot find name 'foo'. For optional chaining foo must not be undefined
add a note about typeof foo for undeclared variables. especially if you're already doing TS, it should never be allowed, and your linter should force rejection
note that use this ? when you are 100% sure it is typescript; t silently has trouble in JavaScript code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.