Why You Can't Narrow "any" in TypeScript

Typescript logo

I ran into an issue using TypeScript recently. In TypeScript you can do typechecks (using typeguards) in your code to effectively “narrow” a type.

I’ll explain - if you have a union type that could be one of several types you may want to “narrow” this in your code so that you know what type your object is after a certain point in the code.

What was surprising to me is that you cannot “narrow” a type of any!

I found a discussion here on stack overflow, and a comment from a TypeScript maintainer here but apparently this is a purposeful design decision.

I’ll show you the code I was trying to do this with - here is a code sandbox, in case you are interested in seeing this in action.

Written on May 26, 2020