Elm's Opaque Types are a powerful tool for narrowing the surface area where you check a constraint. TypeScript's Branded Types give similar

Opaque Types Let You Think Locally

submited by
Style Pass
2021-10-28 04:00:06

Elm's Opaque Types are a powerful tool for narrowing the surface area where you check a constraint. TypeScript's Branded Types give similar functionality but without closing outside use, so you can't be sure the constraints are enforced everywhere. Let's explore the differences to better understand why Elm's Opaque Types are such an important tool.

Strictly speaking, opaque types don't make Elm's type system more sound. Instead, they help you narrow your thinking of how a particular type is used to within a single module. They allow you to check that a constraint is enforced in a single module, rather than having to ensure that a constraint is enforced throughout your entire codebase, both now and in the future.

For example, if you want to ensure that a String actually represents a confirmed email address, that has nothing to do with type soundness - the type is just a String. But if the only way to get a value with type ConfirmedEmailAddress = ConfirmedEmailAddress String is through an HTTP request to a specific server endpoint, then you can trust any value of that type after checking the ConfirmedEmailAddress module and the API endpoint. You just need to make sure that you trust that server endpoint and the ConfirmedEmailAddress module. It's the same idea as [Using elm types to prevent logging social security #'s].

Leave a Comment