Description
Version of emscripten/emsdk:
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 4.0.2 (7591f1c)
clang version 21.0.0git (https:/github.com/llvm/llvm-project 9534d27e3321a3b9e6e79fe6328445575bf26b7b)
Target: wasm32-unknown-emscripten
Thread model: posix
Here is a simple repro case:
#include <emscripten/bind.h>
struct Test {
float x;
std::optional<float> y;
};
void consumeTest(const Test &test) {}
EMSCRIPTEN_BINDINGS(test) {
emscripten::value_object<Test>("Test")
.field("x", &Test::x)
.field("y", &Test::y)
;
emscripten::register_optional<float>();
emscripten::function("consumeTest", &consumeTest);
} // EMSCRIPTEN_BINDINGS
Now from Javascript if I call Module.consumeTest({x: 2})
it fails with the error TypeError: Missing field: "y"
.
I would need to call Module.consumeTest({x: 2, y: undefined})
for this to work.
The whole point of making y
optional is being able to omit it. Also, having to pass undefined
is very brittle, because JSON serialization/deserialization drops undefined fields.
My proposal is to make .field
aware of std::optional
and don't complain when an optional field is missing. Does this make sense?
Aside: It would also be nice for the .d.ts
typescript definitions to use optional fields as well (i.e. y?: number
).