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

An example of what you can implement on top of branded types that I want to share with fellow hackers:

- currencies

You may have some sort of integer representing the number of cents of some currency and you want to avoid doing operations between the wrong currencies (such as adding euros and pesos).

You can create branded types and functions that work on those Euro branded numbers and then decide how to do math on it. Or numbers representing metals and such.

It's useful in other scenarios such as a, idk, strings, you could theoretically brand strings as idk ASCII or UTF-8 or the content of an http body to avoid mixing those up when encoding but I want to emphasize that often many of those hacks are easier to be handled with stuff like dictionaries or tagged unions.

An example of what can be achieved with similar approaches (beware it's oriented for people that are at least amateur practitioners of functional programming) is Giulio Canti's (an Italian mathematician and previously author of t-comb, fp-ts, io-ts, optic-ts, and now effect and effect/schema), the money-ts library:

https://github.com/gcanti/money-ts



As much as I love branding, I would be hesitant to use it for critical math and where you might want to inspect the type at runtime as with money.

Branding is easily circumvented, so it's best as a developer hint that helps document APIs and alerts us to common mistakes as an incremental improvement over primitives.

For money and similar I would use objects and a custom math library.


You can parse before brand thus enhance and enforce runtime correctness.


Another example: inches versus meters. We have lost a mars probe due to a misinterpretation of the numbers: https://www.latimes.com/archives/la-xpm-1999-oct-01-mn-17288...


Thanks, the currency stuff was a great real-world example that crystallized where this would be nice to have at a core level with typescript to severely reduce the odds of doing cross-currency math.


I have seen plenty of currencies come and go in my life: weird to lock that into your codebase.

And I'm struggling to think of where in a codebase I might want to hardcode Pesos or Euros.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

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

Search: