Today I Learned: Destructure Objects in Function Signatures
When modeling types, one thing to keep in mind is to not leverage primitive types for your domain. This comes up when we use a primitive type (like a string) to represent core domain concepts (like a Social Security Number or a Phone Number).
Here's an example where it can become problematic:
There's a bug in this code, where we're trying to send an email to a phone number. Unfortunately, this code type checks and compiles, so we have to lean on other techniques (automated testing or code reviews) to discover the bug.
Since it's better to find issues earlier in the process, we can make this a compilation error by introducing a new type for Email
since not all strings should be treated equally.
One approach we can do is to create a tagged union like the following:
With this in place, we can change our sendEmail
function to leverage the new Email
type.
Now, when we get a compilation error when we try passing in a phoneNumber.
One downside to this approach is that if you want to get the value from the Email
type, you need to access it's value
property. This can be a bit hard to read and keep track of.
Leveraging Object Destructuring in Functions
One technique to avoid this is to use destructuring to get the individual properties. This allows us to "throw away" some properties and hold onto the ones we care about. For example, let's say that we wanted only the phoneNumber
from a Customer
. We could get that with an assignment like the following:
This works fine for assignments, but it'd be nice to have this at a function level. Thankfully, we can do that like so:
If you find yourself using domain types like this, then this is a handy tool to have in your toolbox.