Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> In typecript’s not so strict type system, you can cast anything to the `any` type. And from the `any` type, you can cast it to whichever type you wish

Minor correction: this is really more an issue with the `as` operator. For example these also work:

    user as unknown as NotUser
    user as never as NotUser
`as` let's you cast to arbitrary super- and sub-types. It prevents you from casting to unrelated types directly (here `NotUser`), but you can always use the trick above: Either cast to the top-type (unknown/any) or bottom-type (never) first, then you have something that's a super-type (sub-type) of everything so you are free to cast back down (up) to an arbitrary type.

The potentially unsafe step is the down cast. Up casts should always be safe.

`any` just puts you back into the dynamic typing world. It exists so TypeScript can be gradually adopted in JavaScript codebase. At least the use of `any` can be discouraged with linting. But that doesn't work for `as`. Linters don't understand the difference between safe up- and unsafe down casts. So you can only flag all uses of `as` or none.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: