4 ms·
I don't see why. I greatly prefer typescript's structural typing for almost everything. But id's in data models are an exception, so I use branding for those. I
by kristiandupont 2y ago
I don't see why. I greatly prefer typescript's structural typing for almost everything. But id's in data models are an exception, so I use branding for those. It works perfectly, the only overhead is in the write-once declaration and now I am protected from accidentally using an AccountId where a MemberId was expected, even though they are both just strings.
- cush 2y agoYes! I've wanted this in Typescript for ages! Is it possible to brand primitives though?
- kristiandupont 2y agoYes you can, it works just the same :-)
- amatecha 2y agoHow do ids of different types accidentally get into a place they shouldn't be? Is this simply a case where someone mistakenly passes along a property that happens to be called "id", not noticing it's an account id rather than a member id (as in, an implementation error)?
- mason55 2y agoYeah, or what's more likely is that you originally used an AccountID everywhere, but then you decided that you want to use a UserAccountID. So you update your functions but you miss a spot when you're updating all your call sites. Or you have a client library that you use to interact with your API, and the client library changes, and you don't even notice. Or you change the return type of a function in a library, and you don't even know who all the callers are, but it sure would be nice if they all get a build error when they update to the latest version of your library. Lots and lots and lots of ways for this to happen in a medium+ sized project that's been around for more than a few months. It's just another way to leverage the power of types to have the compiler help you write correct code. Most of the time most people don't mess it up, but it sure feels good to know that it's literally impossible to mess up.
- klysm 2y agoThis kind of mistake is quite easy to make, especially when somebody writes a function that takes several IDs as arguments next to each other. I've seen it happen a number of times over the years
- z3t4 2y agofunction foo(customerId, itemId, orderId) { if(!customer[customerId]) throw new Error("Customer with id=" + customerId + " does not exist"); if(!item[itemId]) throw new Error("Item with id=" + itemId + " does not exist"); if(!order[orderId]) throw new Error("Order with id=" + orderId+ " does not exist"); } Just an example of how you can detect errors early with defensive programming.