Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm: Type alias for JSON with "type" property

Tags:

elm

I have some JSON with a "type" property that I want to import into Elm. e.g., { "id": "abc", "type": "thing" } However if I define a type alias with type as a property, the compiler complains. e.g.,

type alias Foo = {
      id: String
    , type: String
}

produces

It looks like the keyword `type` is being used as a variable.

3│     , type: String
              ^
Rename it to something else.

Seriously? I have to rename the property? Is there no way to quote or escape it so it will compile?

like image 425
noah Avatar asked Jan 20 '16 09:01

noah


2 Answers

Yes, type is a reserved keyword and cannot be used as a field name in a record.

In Elm and Haskell, the most common thing to do in your case seems to be to append a single quote, so it becomes type', and your type definition becomes

type alias Foo =
  { id: String
  , type': String
  }

This has its origin in the prime symbol from mathematics. It may look odd at first but it is valid syntax.

You can then use the following Json Decoder to translate the JSON into Foo:

fooDecoder =
  Json.object2
    Foo
    ("id" := Json.string)
    ("type" := Json.string)

Notice that the exact field name in Elm does not need to match the JSON field name.

Rarely will you find a language that lets you use keywords as variable names unescaped. This behavior is not unique to Elm.

like image 124
Chad Gilbert Avatar answered Oct 01 '22 21:10

Chad Gilbert


You can now escape the keyword with an underscore.

ex.

type alias Foo =
  { id: String
  , type_: String
}
like image 28
Dwayne Forde Avatar answered Oct 01 '22 21:10

Dwayne Forde