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

ahh interesting, that seems like a pretty significant difference. just to clarify, this means that you wouldn't be able to do things like:

if (my_var instance_of MyCustomType)

in TS, but you could in normal statically typed languages, correct?



It's a bit more complicated than that because of JS's prototype-oriented object system. If MyCustomType is a proper prototype (say you built it with the class keyword) you can certainly instanceof it. (That said there are strange edge cases where statically typed class-based object intuition falls down against prototype-oriented reality.)

The issues tend to start cropping up as you get further into TS-specific types like generic types. In a statically typed language you can inquire about the specifics of an implementation of a generic directly, and often even dispatch directly on that type. JS has no concept of your generic wrapper type and you need some other flag or logic to determine the runtime type of your generic code.


I shouldn't have included nominal typing - it seems the instanceof operator actually works, e.g. see http://stackoverflow.com/questions/24705631/typescript-myobj....

But in TS itself structural typing is used everywhere for actual type checking (except for classes with private members), and from my understanding there's no way to have TS help you check at runtime whether a type is structurally compatible with a value.


As long as you're not doing type casting or any funny reflection, you can write that code and it'll be caught at compile-time.

I wrote a library [1] that does this in a readable pattern-matching way, hope you find it useful!

[1] https://github.com/jiaweihli/rematch




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

Search: