Hacker News new | past | comments | ask | show | jobs | submit login

Good points!

Seems like for "6. Optional properties"

One should rather use tagged unions (see: Abstract Data Types, variants) that are usually written like this in TS:

    type Product = 
     | { type: 'digital', id: string, sizeInMb: number }
     | { type: 'physical', id: string, weightInKg: number }
At least I find it more elegant, concise and fun to work with :)



Also, for using type guards to validate incoming data, check out https://github.com/pelotom/runtypes.

Or if brave enough to dive into the deep end of FP, io-ts is nice. https://github.com/gcanti/io-ts


Well it all depends on how you're expecting your types to be extended. I'm not sure what TypeScript's support for interfaces is like but it might make sense to have interfaces for both (just in case you ever have a product that's both physical and digital).

Tagged unions might get a bit messy if you ever need to extend them, but sometimes you simply have some source / sink of data that requires a variant type.


According to https://github.com/microsoft/TypeScript/wiki/Performance#pre... using union types in your example vs interfaces like #6 is bad for compilation performance.


As the docs mention, the effect is only material when there's a non-trivial number of union elements. For unions containing only a handful of elements the effect is inconsequential.


I like this way more. Wayyy more.




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

Search: