const arr = ['foo'] as ['foo']
This wound up being useful in a situation that boiled down to: type SomeObj = { foo: string, bar: string }
export const someFn = (props: (keyof SomeObj)[]) => {}
// elsewhere
const props = ['foo'] as ['foo']
someFn(props)
In a case like that `as const` doesn't work, since the function doesn't expect a readonly argument. Of course there are several other ways to do it, but in my case the call site didn't currently import the SomeObj type, so casting "X as X" seemed like the simplest fix.But mostly it just gave me a chuckle. I tried it because it seemed logical, but I didn't really think it was going to work until it did..
const props: ['foo'] = ['foo']
const arr = ["foo" as const]
It really should be called "vaguely typed script"
If it were this strict out-of-the-box, it probably would have been hated since most devs don't really want to deal with static typing.
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
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
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.
If you were going to rely on that anyway, why not just use JavaScript as is and avoid the boilerplate from typescript
It's not like using js at all, not that I think there's anything wrong with it, if that's your jam.
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)
Octoth0rpe•3h ago