Elm Language Type Aliases


Example

Sometimes we want to give a type a more descriptive name. Let's say our app has a data type representing users:

{ name : String, age : Int, email : String }

And our functions on users have type signatures along the lines of:

prettyPrintUser : { name : String, age : Int, email : String } -> String

This could become quite unwieldy with a larger record type for a user, so let's use a type alias to cut down on the size and give a more meaningful name to that data structure:

type alias User =
    { name: String
    , age : Int
    , email : String
    }


prettyPrintUser : User -> String

Type aliases make it much cleaner to define and use a model for an application:

type alias Model =
    { count : Int
    , lastEditMade : Time
    }

Using type alias literally just aliases a type with the name you give it. Using the Model type above is exactly the same as using { count : Int, lastEditMade : Time }. Here's an example showing how aliases are no different than the underlying types:

type alias Bugatti = Int

type alias Fugazi = Int

unstoppableForceImmovableObject : Bugatti -> Fugazi -> Int
unstoppableForceImmovableObject bug fug =
    bug + fug

> unstoppableForceImmovableObject 09 87
96 : Int

A type alias for a record type defines a constructor function with one argument for each field in declaration order.

type alias Point = { x : Int, y : Int }

Point 3 7
{ x = 3, y = 7 } : Point

type alias Person = { last : String, middle : String, first : String }

Person "McNameface" "M" "Namey"
{ last = "McNameface", middle = "M", first = "Namey" } : Person

Each record type alias has its own field order even for a compatible type.

type alias Person = { last : String, middle : String, first : String }
type alias Person2 = { first : String, last : String, middle : String }

Person2 "Theodore" "Roosevelt" "-"
{ first = "Theodore", last = "Roosevelt", middle = "-" } : Person2

a = [ Person "Last" "Middle" "First", Person2 "First" "Last" "Middle" ]
[{ last = "Last", middle = "Middle", first = "First" },{ first = "First", last = "Last", middle = "Middle" }] : List Person2