从 Purescript Record 转换为 JS 对象

converting from Purescript Record to a JS object

我正在尝试将 Record 转换为 vanilla JS 对象

module MyModule where

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

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

当我从 JS 访问对象时

MyModule.phil

它包含我不感兴趣的其他属性(value0)

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

如何将 Records 从 Purescript 世界编组到 JS?

Purescript By Example10.16 部分,Phil Freeman 展示了 newtype 包装记录的示例:

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

然后在 10.18 部分,他写道:

"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."

我认为您需要深入了解 psc 生成的内容才能真正体会到这一点。我们将 data 换成 newtype,

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

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

这编译为

// 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
};