Search code examples
reactjstypescriptoptional-chaining

Is only one '?' property enough in my case with TypeScript Optional chaining


In my React and TypeScript (version "^3.9.9") app I am mapping over some items to render the list/teasers:

    {data?.getItems.items
      .map((teaser) => (
        <Teaser
          key={teaser.id}
          title={teaser.extraData?.title || video.title}
          label={teaser.extraData?.label}
        />
      ))}

extraData object can be null queried with Graphql from api. I am using Typescripts Optional chaining.

It's enough to prevent my app from breaking to add teaser.extraData?.title.

But what is the difference between teaser?.extraData?.title and teaser.extraData?.title and what should I use to be safe?


Solution

  • But what is the difference between teaser?.extraData?.title and teaser.extraData?.title and what should I use to be safe?

    The first one will evaluate to undefined without error if teaser, itself, is null or undefined (collectively: "nullish"). The second will throw an error in that case, because you've chained (non-optionally) from teaser.

    The way optional chaining works, the entire property access operation is short-circuited (resulting in undefined) at the point of the optional chain if the thing just before the optional chain is null or undefined.

    So in your example, apparently teaser is always non-nullish, but teaser.extraData is sometimes nullish. So you only need optional chaining after teaser.extraData, not teaser, in this specific case.


    Side note: Optional chaining is part of JavaScript now, it was added to the ES2020 specification after having been natively implemented by all major engines. It's not just TypeScript (anymore).