Skip to content

Custom typed parameters #3107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
scallaway opened this issue Oct 12, 2022 · 5 comments
Closed

Custom typed parameters #3107

scallaway opened this issue Oct 12, 2022 · 5 comments

Comments

@scallaway
Copy link

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.

@katopz
Copy link

katopz commented Oct 16, 2022

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.

@Liamolucko
Copy link
Collaborator

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:?}")
}

@daxpedda
Copy link
Collaborator

Maybe we can improve this at some point in the future, so I'm gonna leave it open.

@scallaway
Copy link
Author

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

@daxpedda
Copy link
Collaborator

Resolved by #4394.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants