Record with optional and mutable fields
在文档中:https://bucklescript.github.io/docs/en/object.html包含带有可变字段和可选字段的记录示例。当我尝试同时使用两者时,它会失败:
编译:
1 2 3 4 5 6 7
| type person = {
mutable age : int;
job : string;
} [@@bs .deriving abstract ]
let joe = person ~age:20 ~job:"teacher"
let () = ageSet joe 21 |
添加[@bs.optional]属性:
1 2 3 4 5 6 7
| type person = {
mutable age : int;
job : string [@bs .optional ];
} [@@bs .deriving abstract ]
let joe = person ~age:20 ~job:"teacher"
let () = ageSet joe 21 |
错误消息:
Line 7, 20:
This expression has type unit -> person
but an expression was expected of type person
第7行是ageSet行。
我在这里错过了什么吗?
我重新阅读了文档,这是我错过的部分
Note: now that your creation function contains optional fields, we mandate an unlabeled () at the end to indicate that you've finished applying the function.
1 2 3 4 5 6 7
| type person = {
mutable age : int;
job : string [@bs .optional ];
} [@@bs .deriving abstract ]
let joe = person ~age:20 ~job:"teacher" ()
let () = ageSet joe 21 |
- Ocaml函数要求最后一个参数始终是非可选的。因此,当您拥有的函数不是这种情况时,一般的解决方案是添加一个哑元参数。 bs.optional别无选择,只能在这里这样做。