Custom typed parameters
I'm looking to supply a specific typing for parameters to the function that I'm writing in Rust and exposing to TS.
In an ideal world, I'd love for the function to accept a Vec<MyJsStruct> where MyJsStruct contains two String fields, but that doesn't look like it's possible at the moment.
To step around this, I'm using JsValue and serde_wasm_bindgen::from_value which is working quite well. However, the generated wasm.d.ts file types the parameter to my function as any, which really isn't ideal when using TypeScript.
I was wondering if there's a way to annotate the function that I'm writing in order to specify the type of the parameter that it accepts, when the definition file is generated?
I can extend the definition file on the TypeScript side, but being able to do this completely in Rust would be much better.
Maybe this help https://github.com/fjarri/wasm-bindgen-derive/blob/master/src/lib.rs#L60-L103 BTW, I didn't have time to try it yet just found it today and post it here for the record.
This can be done with a combination of #[wasm_bindgen(typescript_type)] and #[wasm_bindgen(typescript_custom_section)]:
use serde::Deserialize;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(typescript_custom_section)]
const _: &str = "
interface MyJsStruct {
a: string,
b: string,
}
";
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "MyJsStruct[]")]
pub type MyJsStructArray;
}
#[derive(Debug, Deserialize)]
struct MyJsStruct {
a: String,
b: String,
}
#[wasm_bindgen]
pub fn debug_array(array: MyJsStructArray) -> String {
let array: Vec<MyJsStruct> = serde_wasm_bindgen::from_value(array.into()).unwrap();
format!("{array:?}")
}
Maybe we can improve this at some point in the future, so I'm gonna leave it open.
This can be done with a combination of #[wasm_bindgen(typescript_type)] and #[wasm_bindgen(typescript_custom_section)]:
Oh this looks intersting - will give it a try