pub fn serialize_hashmap_as_object<V, S>(
val: &HashMap<String, V>,
serializer: S,
) -> Result<S::Ok, S::Error>where
V: Serialize,
S: Serializer,Expand description
Serializer fn that serializes HashMap as k/v object. in js it would be plain js object and not js Map.
The HashMap’s entry values should themselves impl Serialize as well.
This provides great level of flexibilty to specify a specific property of the given type and not all of the properties to be serialized as js plain object instead of js Map when wasm_bindgen convert traits are implemented for the given type by using impl_wasm_traits
Example:
ⓘ
#[derive(serde::Serialize, serde::Deserialize, Tsify)]
struct A {
#[cfg_attr(
target_family = "wasm",
serde(serialize_with = "serialize_hashmap_as_object"),
tsify(type = "Record<string, number>")
)]
field: HashMap<String, u8>,
}
#[cfg(target_family = "wasm")]
impl_all_wasm_traits!(A);
#[wasm_bindgen]
pub fn some_fn() -> A {
let mut rust_map = HashMap::new();
rust_map.insert("key".to_string(), 1);
rust_map.insert("otherKey".to_string(), 2);
// in js when some_fn() is called the result will be:
// { field: { key: 1, otherKey: 2 } }
A { field: rust_map }
}