1

EDIT: Existing answers are 2 and 5 years old (from 2017 and 2014).

How can I shorten the following statement

  ratingsExisting(): boolean {
    return (
      this.fromAPIData.book &&
      this.fromAPIData.book.misc &&
      this.fromAPIData.book.misc.ratings &&
      this.fromAPIData.book.misc.ratings.length > 0
    );
  }

so that I don't receive errors if any of the properties is null?

3
  • 1
    Read this article about Optional Chaining in TypeScript Commented Mar 28, 2019 at 10:43
  • 1
    You are a bit to early ... this.fromAPIData?.book?.misc will hopefully be part of both JS and TS soon ... till then you have to fall back to other syntactic sugars shown in the dupe. Commented Mar 28, 2019 at 10:46
  • 1
    Checking that each of these properties exist can be accomplished with the Underscore library. So _.has(this.fromAPIData, 'book.misc.ratings.length) Commented Mar 28, 2019 at 15:54

0