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:
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.
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.
- 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