Tim Fairbrother Tim Fairbrother - 2 months ago 7
Javascript Question

converting from Purescript Record to a JS object

I am trying to convert a Record to a vanilla JS object

module MyModule where

data Author = Author { name :: String, interests :: Array String }

phil :: Author
phil = Author { name: "Phil", interests: ["Functional Programming", "JavaScript"] }


when I access the object from JS

MyModule.phil


it contains other properties that I am not interested in (
value0
)

{"value0":{"name":"Phil","interests":["Functional Programming","JavaScript"]}}


how do you marshal the Records from the Purescript world to JS?

Answer

In section 10.16 of Purescript By Example, Phil Freeman shows an example of a newtype wrapping a record:

newtype FormData = FormData 
   { firstName :: String
   , lastName  :: String
   , street    :: String
   , city      :: String
   , state     :: String
   , homePhone :: String
   , cellPhone :: String 
   }

Then in section 10.18, he writes:

"The FormData type is a newtype for a record, so a value of type FormData passed to JSON.stringify will be serialized as a JSON object. This is because newtypes have the same runtime representation as their underlying data."

I think you need to peek under the hood and look at what psc generates to really appreciate this. We'll swap data for newtype,

newtype Author = Author { name :: String, interests :: Array String }

phil :: Author
phil = Author { name: "Phil", interests: ["Functional Programming", "JavaScript"] }

and this compiles to

// Generated by psc version 0.9.2
"use strict";
var Author = function (x) {
    return x;
};
var phil = {
    name: "Phil",
    interests: [ "Functional Programming", "JavaScript" ]
};
module.exports = {
    Author: Author,
    phil: phil
};
Comments