by culi · 1y ago · 0 comments
const cast = <A, B,>(a: A): B => a as unknown as B;
should never be used in a professional codebase. The post even admits (though, in my opinion, understates) as much:> If you're holding it right, these things don't come up, and your code genuinely is much much safer than if you used raw Javascript.
Just wanted to highlight this point I feel needs to be underscored
Mostly true.
But most system also ingest external data -- that data truly is "unknown" until you parse/validate it. Once you do parse/validate it, you're going to want it to have the correct type.
You shouldn't "never" use. You should only use it in limited, constrained ways, and always with other controls that are sufficient to ensure it's correct.
Even then, a solid validation/parsing library like Zod is a better choice than casting, it is much less error prone at ensuring you have the right type applied.
Beyond that boundary, casting with `as unknown` is a massive code smell and often introduces any further use of that data to invalid type errors. I'll refer to this as "force casting", because simply casting "x as T" with sufficient strictness configured will still fail type checking if x is not compatible with T, and that can be fine for certain cases like reducing a complex type or giving an inferred parser type a form that fits your domain types.
Developers that force cast too readily can end up creating hundreds or even thousands of type errors in the codebase over time, and they are pretty quickly revealed once you peel away the casting. The same is true when starting from an `any`, where every reference thereon is equivalent to a force cast.
There can be some complex typing scenarios that do require it, but even then a good type guard works better even if certain cases can be semantically equivalent, you can write tests around guards as they're just functions, ensuring some logical correctness to the typing.
The simplest but maybe odd way to judge whether a casting is used the wrong way is to ask "are you lying to the type system?". If so, how can you better portray that type correctly (validation that determines a correct type for you (e g. Zod) or type guards).
(Personally, I'm not convinced zod itself is the way to go -- I'm suspicious of its lack of stability. The last thing I want to do is redevelop the boundaries of my system in a few years because zod 4 has been killed off in favor of zod 5, and then again in a few more years for zod 6, etc.)
Absolutely. And there are tools like Zod or e2e type safety solutions to solve this exact problem. And otherwise that data will come in as `any` or already as `unknown` so there will never be a use case for `as unknown as B`. This only happens when the data has already been assigned a type (here, the type is A). Now you're working on recasting it to fix your mistake instead of fixing the core issue of the incorrectly typed data.
The `A as unknown as B` workaround is only relevant when TypeScript believes A and B are so drastically different that they have nothing in common and shouldn't be cast as each other. The reason TypeScript believes that is either because it's true or because you made some earlier mistake.
TL;DR: This article is about fixing your own mistyping and not about typing something that lacks any. It's not about the boundaries of your application but about the internal workings
Maybe my years of contributing to undisciplined codebases has made me bitter but TypeScript has ways to solve these problems and it hurts to see more attention brought to hacks than the interesting (and underdocumented) solutions TypeScript already has. Given that roughly half of the documentation is in the damn changelog, TypeScript is especially in need of independent content that highlight features (not hacks) of the language
If you have complex types, it's sometimes the easiest way to do what you want, and it's perfectly safe as long as you are 100% sure that the types are compatible.
For example, where you have a fluent-style API where each method modifies the types it's unavoidable to end up using that kind of cast
There are certainly ways to guard against that, but most of them involve some amount of accepting that the type checker produces errors for a reason.
Bear in mind, most changes that could cause issues will still be caught by the type checker in whatever object you're casting to. Obviously it should not be overused where not needed, but it's almost always used in fluent apis because there's no better way (that I know of, at least)
Got an example?
That was funny to read
To give you an example from a popular open source ts-heavy project:
https://github.com/elysiajs/elysia/blob/94abb3c95e53e2a77078...
The `return this as any` there, which effectively casts it to the same type this had, but with the added get route is perfectly safe, it works, and will never be a problem by itself.
Tbh I'm not paid by this company enough to spend time breaking down the correct solution but it would involve validating and discriminating the result of `this.add`.
This code is NOT type-safe and will be harder to maintain. Someone will make a change in the future that changes the possible results of `this.add` and TypeScript will not be able to warn you about the consequences of that change.
If you were going to rely on that anyway, why not just use JavaScript as is and avoid the boilerplate from typescript
I think a more concrete example would be necessary but I highly doubt there isn't a more elegant solution using unions and discriminators
> it's sometimes the easiest way to do what you want
This intention is exactly what leads to unmaintainable typescript codebases imo. Thinking you "know better than TypeScript". TS thinks what it thinks for a reason. Usually that reason is past decisions you made
I also don't think it can be perfectly safe. Use a validator if you want it to be perfectly safe