TypeScript, JSON.parse, & undefined: Failing Gracefully when Working with JSON Data in TypeScript

Today at work I have some JSON data which I need to parse with JSON.parse, and need to make sure that my code doesn’t crash my company’s app if for some reason our API doesn’t serve back what I’m expecting. Most of the company’s code which deals with fetching data from our API has already been written, but for this assignment I’m having to make my own networking request and handle all of this stuff myself.

So that’s what brings me here now writing this blog post! I think I have a fairly nice fail-safe way of dealing with JSON, JSON.parse, and unknown values/properties that I prototyped this afternoon on repl.it. Take a look at my code snippet below if you need a similar solution. Happy hacking!

const json = '{"foo": { "bar": { "baz": {"a": 1, "b": 2, "c": 3}}}}';
const parsedJSON = JSON.parse(json);
* DANGER! This line will run, but is not fail-safe, could crash if foo, bar,
* baz or a is missing or undefined
// This line will fail gracefully foo, bar, baz, or b is missing/undefined
// This line fails gracefully
// DANGER! DANGER! This line will crash
// console.log(parsedJSON?.foo?.bar?.baz?.x.y.z);