3 ms·
Good points! Seems like for "6. Optional properties" One should rather use tagged unions (see: Abstract Data Types, variants) that are usually written like th
by elnygren 6y ago
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 :)
- agloeregrets 6y agoI like this way more. Wayyy more.
- elnygren 6y agoAlso, for using type guards to validate incoming data, check out https://github.com/pelotom/runtypes 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 https://github.com/gcanti/io-ts
- bengalister 6y agoAccording to https://github.com/microsoft/TypeScript/wiki/Performance#preferring-base-types-over-unions https://github.com/microsoft/TypeScript/wiki/Performance#pre... using union types in your example vs interfaces like #6 is bad for compilation performance.
- bryzio 6y agoAs 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.
- contravariant 6y agoWell 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.