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?
The main benefit of using a type alias for this is when we write the type annotations for the update and view functions. Writing Msg -> Model -> Model is so much nicer than the fully expanded version! It has the added benefit that we can add fields to our model without needing to change any type annotations.
A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.
Advertisements. The Type System represents the different types of values supported by the language. The Type System checks validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected.
A type alias is usually used to simplify declaration for complex types, such as parameterized types or function types. Let's explore examples of those aliases and also look at some illegal implementations of type aliases.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With