假设我有PureScript代码中的用户记录,类型如下:
{ id :: Number
, username :: String
, email :: Maybe String
, isActive :: Boolean
}
CommonJS模块源于PureScript代码。导出的与用户相关的函数将从外部JavaScript代码中调用。
在JavaScript代码中,“用户”可能表示为:
var alice = {id: 123, username: 'alice', email: 'alice@example.com', isActive: true};
email
可能为 null
:
var alice = {id: 123, username: 'alice', email: null, isActive: true};
email
可以省略:
var alice = {id: 123, username: 'alice', isActive: true};
isActive
可以省略,如果省略,则默认为 true
:
var alice = {id: 123, username: 'alice'};
id
有时候是一个数字字符串:
var alice = {id: '123', username: 'alice'};
以上五种 JavaScript 表示形式是等价的,应该产生等价的 PureScript 记录。
我该如何编写一个函数,它接受一个 JavaScript 对象并返回一个用户记录? 它将使用空值或省略的可选字段的默认值,将字符串 id
强制转换为数字,并在缺少必需字段或值类型错误时抛出异常。
我看到两种方法可以使用:一种是在 PureScript 模块中使用 FFI,另一种是在外部 JavaScript 代码中定义转换函数。后者似乎有些麻烦:
function convert(user) {
var rec = {};
if (user.email == null) {
rec.email = PS.Data_Maybe.Nothing.value;
} else if (typeof user.email == 'string') {
rec.email = PS.Data_Maybe.Just.create(user.email);
} else {
throw new TypeError('"email" must be a string or null');
}
// ...
}
我不确定FFI版本会如何工作。我还没有处理过effects。
很抱歉这个问题不是非常清楚。我还没有足够的理解来知道我想要知道什么。
x
成为数字或数字字符串? - davidchambersdata SoN = S String | N Number
然后为类型SoN
编写一个IsForeign
实例,使用<|>
运算符来组合这两个选项:read f = S <$> readString f <|> N <$> readNumber f
- Phil Freeman