Why You Can't Narrow "any" in TypeScript
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
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.