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?
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.
You can now escape the keyword with an underscore.
ex.
type alias Foo =
{ id: String
, type_: String
}
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