elm

Difference in Elm between type and type alias?


In Elm, I can't figure out when type is the appropriate keyword vs. type alias. The documentation doesn't seem to have an explanation of this, nor can I find one in the release notes. Is this documented somewhere?


Solution

  • How I think of it:

    type is used for defining new union types:

    type Thing = Something | SomethingElse
    

    Before this definition Something and SomethingElse didn't mean anything. Now they are both of type Thing, which we just defined.

    type alias is used for giving a name to some other type that already exists:

    type alias Location = { lat:Int, long:Int }
    

    { lat = 5, long = 10 } has type { lat:Int, long:Int }, which was already a valid type. But now we can also say it has type Location because that is an alias for the same type.

    It is worth noting that the following will compile just fine and display "thing". Even though we specify thing is a String and aliasedStringIdentity takes an AliasedString, we won't get an error that there is a type mismatch between String/AliasedString:

    import Graphics.Element exposing (show)
    
    type alias AliasedString = String
    
    aliasedStringIdentity: AliasedString -> AliasedString
    aliasedStringIdentity s = s
    
    thing : String
    thing = "thing"
    
    main =
      show <| aliasedStringIdentity thing