Hacker News new | ask | show | jobs
by mpeg 239 days ago
Yes of course the types could change in the future, and the forced cast might cause issues. I wish there was a better way, but this is an acceptable tradeoff.

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)

1 comments

> it's almost always used in fluent apis because there's no better way (that I know of, at least)

Got an example?

Yep, I sent one in another comment https://github.com/elysiajs/elysia/blob/94abb3c95e53e2a77078...

This is not the easiest to follow code, but it's very similar to what you'd find in any fluent web router, the idea is that you have say an App class, which has a Routes generic, then on every route you add you compose the return types by returning this as App<Routes & NewRoute>, the thing is in the most simple cases you can probably do this cast directly and it will be fine, but as you add more features (things like extensibility with plugins, ability to merge to other app routes, etc..) you might eventually run into limitations of the type system that require a escape hatch like "as unknown" or "as any"

It's not the only case in which you might use it, but I think Elysia is a great example as it does some really interesting things with the type system to provide great DX

Thanks. I'm not going to be very specific here because I'm too lazy to dig into that giant type, but if they want that method implementation to work without type assertions then the `add` method would need to be typed as an assertion function[1] so the type system can understand that it narrows its argument[2].

Here's an example: https://tsplay.dev/w8y9PN

[1]: https://www.typescriptlang.org/docs/handbook/release-notes/t...

[2]: Doing this isn't safe anyway because it mutates an object in a type-relevant way while there may other variables referring to it (the safe thing to do is return a new `Elysia` instance from `get`), but that's beside the point.

That's really interesting with the assertion function, I've not seen that done much, thanks!