TypeScript: Custom Type Guards
Keep the Types Intact
Did TypeScript ever annoy you with the error Object is possibly undefined
even if you filter out all the undefined
values, if yes then this post is for you.
Code Setup
Let’s quickly set up a very basic example to see how we can get to such a situation.
In the above example, we have an array of Items
and list of itemIds
, and we are trying to get the metadata of the itemId
. When you run this code and hover over items
, TypeScript will tell you that the variable items
is of type (Item | undefined)[]
which makes sense as some id’s
won’t match and return undefined so far so good, now the undefined items in the array are of no use to us and we don’t want to deal with the undefined errors when further referring the items
variable in our codebase, so let's quickly fix this by filtering out all the undefined values.
Great, now we can easily loop over the items array and process it without having to deal with undefined values, let’s quickly try it.
Wait but why? we already handled this above, let’s hover over items
and see its type
The problem is that the .filter
method will always return an array of the type with which you initially started so in our case it was Item | undefined
which makes sense now but how do we fix this 🤔
Type Guards to the Rescue
This is where TypeScript custom type guards come to the rescue, a custom type guard is basically a function that’s return type is a type predicate. It’s a very simple and intuitive approach for fixing the above problem properly, let’s see it in action.
And that’s how you can filter out the undefined values properly in TypeScript with type guards and keeping the types intact in your codebase. This same approach can be extended to a use-case where you are dealing with a Union type and you want to make sure you are accessing the right properties of the instance of that type.
I hope this post helps you in your journey with TypeScript. As always do share your thoughts on this approach in the comments below and feel free to connect with me on Twitter.