Description
Environment:
rustc
: 1.78web-sys
version: 0.3.77- Build tool:
trunk
0.21.13 - Target:
wasm32-unknown-unknown
- OS: Fedora Linux
Problem Description:
When compiling Rust code targeting wasm32-unknown-unknown
using trunk build
, I encountered a contradictory E0308: mismatched types
error when calling web_sys::RequestInit::set_body
.
The code was preparing an optional request body as an Option<JsValue>
and then attempting to pass it to opts.set_body(...)
where opts
is a web_sys::RequestInit
.
-
Error Message: Stated the method expected a direct reference:
error[E0308]: mismatched types --> src/client/api.rs:XX:YY | XX| opts.set_body(some_variable); | -------- ^^^^^^^^^^^^^ expected `&JsValue`, found `Option<&JsValue>` | | | arguments to this method are incorrect | = note: expected reference `&JsValue` found enum `std::option::Option<&JsValue>`
-
**
note:
:** Simultaneously, the note pointing to the method definition suggested a different signature requiring anOption
:note: method defined here --> /home/user/.cargo/registry/src/index.crates.io-.../web-sys-0.3.77/src/features/gen_RequestInit.rs:22:12 | 22 | pub fn set_body(this: &RequestInit, val: Option<&::wasm_bindgen::JsValue>); // <-- Signature in note differs from primary error | ^^^^^^^^
Investigation & Resolution:
- Attempts to satisfy the signature shown in the
note:
by passingSome(&jsvalue)
or usingoption.as_ref()
to create anOption<&JsValue>
still failed compilation, resulting in the primary error demanding&JsValue
. - Consulting the
web-sys
0.3.77 documentation and source code confirmed that the actual current signature for the method is:pub fn set_body(&self, val: &JsValue)
- This confirms that the rimary error message (
expected &JsValue
) was correct, and the diagnosticnote:
pointing to the definition was misleading. - The working code that successfully compiles involves handling the
Some
andNone
cases explicitly to always pass a&JsValue
, matching the actual signature:// body_for_request is Option<JsValue> if let Some(ref body_value) = body_for_request { opts.set_body(body_value); // Pass &JsValue directly when Some } else { opts.set_body(&JsValue::NULL); // Pass reference to JsValue::NULL when None }
Summary:
I am are sharing this information in case others encounter a similar contradictory diagnostic message for web_sys::RequestInit::set_body
. The key finding is that the actual method signature expects &JsValue
, and the diagnostic note:
suggesting Option<&JsValue>
appears to be inaccurate for web-sys
version 0.3.77. The correct approach is to pass &JsValue
directly or &JsValue::NULL
.