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?

  • 1
    Read this article about [Optional Chaining in TypeScript](https://medium.com/inside-rimeto/optional-chaining-in-typescript-622c3121f99b) – Alex Mar 28 '19 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. – Jonas Wilms Mar 28 '19 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) – blorkfish Mar 28 '19 at 15:54

0 Answers0