wasm-bindgen icon indicating copy to clipboard operation
wasm-bindgen copied to clipboard

TryFromJsRef trait Proposal

Open rafaelbeckel opened this issue 4 months ago • 4 comments

I found myself needing something like this when trying to pass a custom object through the FFI boundary without transferring ownership to Rust:

pub trait TryFromJsRef {
    /// The type returned in the event of a conversion error.
    type Error;

    /// Performs the conversion.
    fn try_from_js_ref(value: &JsValue) -> Result<&Self, Self::Error>;
}

When I call a method that takes a &JsValue and use try_from_js_value to get my object internally, it consumes the object, and the second call to the same function fails. So, I feel an equivalent try_from_js_ref is needed, unless there is already a canonical way to achieve that that I'm not aware of.

This PR implements it. Reviews & feedback are welcome!

rafaelbeckel avatar Sep 14 '25 05:09 rafaelbeckel

Does dyn_ref not work for this use case?

guybedford avatar Sep 14 '25 22:09 guybedford

How to use it with custom structs?

try_from_js_value works out of the box (but consumes the value). When I use dyn_ref, I get:

"The trait wasm_bindgen::JsCast is not implemented for T"

rafaelbeckel avatar Sep 21 '25 03:09 rafaelbeckel

Ahh, custom structs don't implement instanceof, so you'd need to use the unchecked variant in that case - unchecked_ref.

guybedford avatar Oct 01 '25 21:10 guybedford

Custom classes should certainly work with instanceof though...

guybedford avatar Oct 01 '25 21:10 guybedford