Phantom Type

I'm collecting a handful of useful patterns mostly for my own reference when building safe and maintainable software. I also have a note on the oh-so-handy Builder Pattern.

a ghost stamping papers, digital art --ar 24:9

October is just around the corner and with it, All Hallows' Eve. What a better time to explore phantom types?

What is so spooky?

In Elm, a phantom type is a type with a type parameter that is unused by any constructors of the type. I like to think of it as a way to tag data for better type safety.

This gives you the ability to constrain the inputs of a function and impose conditions at boundaries.

type Item a = This Config | That

a is the type parameter and as you can see, it does not get used in any of the constructors.

When is this useful?

Maybe you have an Item that has not been validated. You can tag an item with a Valid or Invalid custom type.

ensure : Item Invalid -> Item Valid

-- upload only takes a valid item
upload : Item Valid -> Cmd Msg

This way we don't accidentally upload bad data.

Phantom Type
Interactive graph
On this page
What is so spooky?
When is this useful?