Ocaml has exactly the same kinds of escape hatches, like Obj.magic or unsafe accessors. The way I see it. it's a matter of community practice more than language capabilities. Typescript in practice has has the safety net of being interpreted rather than compiled, so I guess people tend to abuse its type flexibility more.
But if you write without the escape hatches in both languages, in my experience the safety is exactly the same and the cost of that safety is lower in TypeScript.
A very common example I've encountered is values in a const array which you want to iterate on and have guarantees about. TypeScript has a great idiom for this:
```
const arr = ['a', 'b'] as const;
type arrType = typeof arr[number];
for (const x of arr) {
if (x === 'a') {
...
} else {
// Type checker knows x === 'b'
}
}
```
First off, the escape hatches in TypeScript are way too accessible compared to OCaml: `JSON.parse(...) as MyInterface` is everywhere and completely broken.
And second, you're dismissing the fact that TypeScript is unsound, even worse it is so by design. Easy examples: uninitialized variables holding undefined when their type says they can't [1]; array covariance [2]; and function parameter bivariance, which is part of the TypeScript playground's own example on soundness issues [3] but at least this one can be configured away.
C# and Java made the same mistake of array covariance, but they have the decency of checking for it at runtime.
As for your example, I agree that TypeScript unions and singleton types are powerful, but I can't see what are you speficially missing here that pattern matching and maybe an additional variant type doesn't get you in OCaml. You get exhaustiveness checking and can narrow the value down to the payload of the variant.
Thanks, these are good examples of holes in typescript that I wasn't aware of. I guess I haven't pushed it enough yet to run into them. I agree Ocaml wouldn't fail.
> I can't see what are you speficially missing here that pattern matching and maybe an additional variant type doesn't get you in OCaml. You get exhaustiveness checking and can narrow the value down to the payload of the variant.
A couple things, being constrained to pattern matching in places where imperative programming would be more natural, having to declare lots of special purpose types explicitly vs being able to rely on ad hoc duck typing.
But if you write without the escape hatches in both languages, in my experience the safety is exactly the same and the cost of that safety is lower in TypeScript.
A very common example I've encountered is values in a const array which you want to iterate on and have guarantees about. TypeScript has a great idiom for this:
``` const arr = ['a', 'b'] as const; type arrType = typeof arr[number];
for (const x of arr) { if (x === 'a') { ... } else { // Type checker knows x === 'b' } } ```
I haven't experienced the same with Ocaml