Skip to main content

TypeScript type guard for empty JSON object

· One min read

A 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);
}