DEV Community

Dina Berry
Dina Berry

Posted on • Originally published at dfberry.github.io on

1

TypeScript type guard for empty JSON object

Commit history for a repo on GitHub can be optional, if there are no commits yet. The TypeScript SDK created by the GraphQL CodeGen represents this optionality is represented with an empty object, null, or undefined. If a commit is present, its represented as a nested JSON object with more optional parameters.


```
declare var x: {} | 
    null | 
    undefined | 
    {'a': { ... more optional params } }
```


The empty JSON object, {}, is tricky in JavaScript. There are several examples of testing for an empty object but they generally don't work as type guards in TypeScript for type safety.

Type guard with in

After asking on StackOverlow and getting no response, I reached out to my local TypeScript expert for help.

He helped boil the issue down to the type shown in the previous code block with a type guard using the in keyword:


```
if (x !== null && x !== undefined && "a" in x) { 
    // no null 
    // not undefined 
    // x has property 'a' so it isn't empty 

    console.log(x.a);
}
```


Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay