4 Unconventional Ways to Cast in Typescript
wolfgirl.dev·9h
Flag this post

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 unsou…

Similar Posts

Loading similar posts...