elm

This is not a record, so it has no fields to access?


I have a problem regarding my Elm project. I have this function here, but I have a problem at interval.start and interval.end yielding the error "This is not a record, so it has no fields to access!".

dateToStringForView : Date -> String
dateToStringForView (Date d) =
    case d.month of
        Just m -> monthToString m ++ " " ++ String.fromInt d.year
        Nothing -> String.fromInt d.year

type Interval
    = Interval { start : Date, end : Maybe Date }
view : Interval -> Html msg
view interval = 
    let
        startText =
            div [class "interval-start"] [text (Date.dateToStringForView interval.end)]

        endText =
            case interval.end of
                Just endDate ->
                    div [class "interval-end"] [text (Date.dateToStringForView endDate)]

                Nothing ->
                    div [class "interval-end"] [text "Present"]
        
        lengthText =
            case length interval of
                Just (years, months) ->
                    div [class "interval-length"] [text (String.fromInt years ++ " years, " ++ String.fromInt months ++ " months")]

                Nothing ->
                    text ""
    in
    div [class "interval"]
        [ --startText
        --, endText,
        lengthText
        ]

Solution

  • Interval is not a record type. It's a custom type with a single variant called that has a record as a payload. You either have to unpack the record from the variant when using it, or just not put it in a custom type to begin with.

    To unpack it, simply do:

    view : Interval -> Html msg
    view (Interval interval) = ...
    

    To make Interval a record type (or rather a type alias since record types are structural and don't need to be named):

    type alias Interval = { start : Date, end : Maybe Date }