4 Unconventional Ways to Cast in Typescript Published: 10/22/2025, 10:43:18 PM
I saw a post by qntm and remembered I had a playground with a similar idea. I then expanded that playground into a (probably non-exhaustive) list of ways to cast between arbitrary1 types in Typescript:
Convention: The as Operator
Ah, good ol' as :
const cast = < A , B ,>( a : A ) : B => a as unknown as B ;
We can't just directly do a as B because Typescript is smart enough to warn us about that, at least. That very same error message also says,
If this was intentional, convert the expression to 'unknown' first.
So we can just do that :3
If we were approaching this from a type theoretic perspective, it's already done & dusted, we have the most cut-and-dry demonstration of unsoundness, pack it up go home.
But, what if we couldn't use as ? Can we still get between two completely unrelated types?
... continue reading