Html Msg vs Html msg?

I can’t seem to figure out when you would use Html msg over Html Msg. Clarification and a bit of the internals will be appreciated!

3 Likes

The lower case msg is called a type variable.

The upper case Msg is called a concrete type - its something your application has defined.

So we might have:

view : Html msg
view = div [] []

and

type Msg = Click

view : Html Msg
view = div [ onClick Click ] []

The first one doesn’t produce any events, so its type variable is not bound to anything yet.
The second one produces events of your Msg type, and its type variable is bound to that.

Also note that this compiles ok:

innerView : Html msg
innerView = div [] []

view : Html Msg
view = div [ onClick Click ] [ innerView ]

Here innerView needs to have the type Html Msg to be included in some HTML with that type. That’s ok because the free msg variable can be bound to Msg and the type checking passes.

Make sense?

4 Likes

Yes! I finally understand it better now. Thank you for your time!

I think part of the confusion here is that there are two different things referred to as “message” in the Elm community.

  1. The generic idea of a value that represents an event in the outside world and that will eventually feed into your update function. It shows up as a type variable in several types where it is conventionally written as little “m” msg (e.g. Html msg, Cmd msg)
  2. A user-defined custom type named big “M” Msg

While there’s often a lot of overlap between the two, they are not the same. Msg isn’t a “magic” framework type and types like Html String or Html Int are valid. More subtly, larger projects such as elm-spa-example often have view functions that return values like Html Home.Msg or Html Article.Msg

While the lowercase msg variable name has good intentions of communicating “the type that would go here fills the role of a message (definition 1)”, my experience is that many people read it as “the type that would go here is going to be a Msg (definition 2)”.

Personally, I’ve started using Html a in my own code rather than Html msg to avoid this confusion :slight_smile:

3 Likes

Thank you for your thorough response!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.