Search code examples
rustrust-wasm

How to use #[wasm_bindgen] with a type aliases?


What I'd like to do:

#[wasm_bindgen]
pub type ParseError = parserange::Error;

But the Rust compiler complains:

error: #[wasm_bindgen] can only be applied to a function, struct, enum, impl, or extern block
  --> src/lib.rs:89:1
   |
89 | pub type ParseError = parserange::Error;

I don't want to add the #[wasm-bindgen] attribute in parserange.rs because it's in a separate library that doesn't build with wasm.

Is there a work-around?


Solution

  • The workaround is to wrap the parserange::Error in a tuple struct to create a new type. The downside of this is that all functions defined on parserange::Error that you'd like to use will have to be redefined to call the error sub-object's function. This has all the advantages of creating a new type though, such as exporting in through wasm_bindgen, or implementing traits on a type defined in another crate. More information can be found here