I’m making an API call that 99% of the time has this value defined: awayTeam.record[0].displayValue
The one percent of the time, however, record is not defined or some other nested object is not defined. Is there a clean one line solution to check wether record exists?
I have tried things like this:
<h1> {awayTeam.record[0]?.displayValue || "0-0"} </h1>
and
<h1> {awayTeam.record[0].displayValue ?? "0-0"} </h1>
I have quite a lot of properties like this, so I would like to find a clean solution for this issue. Thanks!
4
Answers
Your solution seems fine and "clean".
If you want to prevent the usage of the optional chaining (‘?’),
You can declare a function that returns a boolean indicating whether a property exists
Using it as the following:
You can define a small function like
and use it like
This way you don’t have to think where to put these question marks.
The one percent of the time, however, record is not defined or some other nested object is not defined.
Read Below Code:
@T.J. Crowder made a comment suggesting optional array chaining:
This is great, but not strictly type-safe in TypeScript because the nullability on array access is swallowed. There is a new array method
at()
which addressed this by returningT | undefined
:You can use