how to explicitly type functions? #3471
-
#[wasm_bindgen]
pub fn into_avatars(v: JsValue) -> JsValue {
let v = serde_wasm_bindgen::from_value(v).unwrap();
let map = group_users(&v);
let sorted = sorted_users(&map);
serde_wasm_bindgen::to_value(&sorted).unwrap()
} // expected:
type User = { id: number; avatar_url: string }
const into_avatars(users: User[]) => string[] // ... Hello, I've searched through the docs but they were about structs, and i wasn't able to make |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
There are two ways you can go about doing this: manually writing out the function definition with If you want to use Alternatively, you can create some imported JS types which don't actually add any functionality over #[wasm_bindgen]
extern "C" {
// note that you'll also need to use #[wasm_bindgen(typescript_custom_section)] to define `User` in the first place
#[wasm_bindgen(typescript_type = "User[]")]
type UserArray;
#[wasm_bindgen(typescript_type = "string[]")]
type StringArray;
}
#[wasm_bindgen]
pub fn into_avatars(v: UserArray) -> StringArray {
let v = serde_wasm_bindgen::from_value(v.into()).unwrap();
let map = group_users(&v);
let sorted = sorted_users(&map);
// note that `unchecked_into` has to be used instead of `dyn_into` here since `dyn_into` would attempt to check that the value is an instance of `StringArray` in JS, which would fail since that type doesn't exist.
serde_wasm_bindgen::to_value(&sorted).unwrap().unchecked_into()
} |
Beta Was this translation helpful? Give feedback.
There are two ways you can go about doing this: manually writing out the function definition with
#[wasm_bindgen(typescript_custom_section]
or using#[wasm_bindgen(typescript_type)]
.If you want to use
#[wasm_bindgen(typescript_custom_section]
, you'll need to first apply#[wasm_bindgen(skip_typescript)]
to your function so thatwasm-bindgen
's automatically-generated TypeScript for the function doesn't conflict with your hand-written one.Alternatively, you can create some imported JS types which don't actually add any functionality over
JsValue
, but have#[wasm_bindgen(typescript_type)]
applied to them to set what type they map to in TypeScript: