Skip to content

What's the idiomatic way to type js closures in d.ts? #3628

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
hillin opened this issue Sep 21, 2023 · 2 comments
Closed

What's the idiomatic way to type js closures in d.ts? #3628

hillin opened this issue Sep 21, 2023 · 2 comments
Labels

Comments

@hillin
Copy link

hillin commented Sep 21, 2023

E.g. in the example of Receiving JavaScript Closures in Exported Rust Functions:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct VecU32 {
    xs: Vec<u32>,
}

#[wasm_bindgen]
impl VecU32 {
    pub fn each(&self, f: &js_sys::Function) {
        let this = JsValue::null();
        for &x in &self.xs {
            let x = JsValue::from(x);
            let _ = f.call1(&this, &x);
        }
    }
}

I'd like to type the f parameter of the each function in the d.ts file, supposedly like this:

each(f: (value: number) => void);
@daxpedda
Copy link
Collaborator

This is currently not supported.

Duplicate of #3107.

@daxpedda daxpedda closed this as not planned Won't fix, can't repro, duplicate, stale Sep 21, 2023
@Liamolucko
Copy link
Collaborator

This is currently not supported.

Yes it is, you can make a custom subclass of js_sys::Function and give it the appropriate typescript_type:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(extends = js_sys::Function, typescript_type = "(value: number) => void")]
    pub type NumberFunc;
}

#[wasm_bindgen]
pub struct VecU32 {
    xs: Vec<u32>,
}

#[wasm_bindgen]
impl VecU32 {
    pub fn each(&self, f: &NumberFunc) {
        let this = JsValue::null();
        for &x in &self.xs {
            let x = JsValue::from(x);
            let _ = f.call1(&this, &x);
        }
    }
}

The same solution works for #3107. (Well, not perfectly, the OP there asked for an attribute on the function rather than having to declare a type, but more or less.)

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

No branches or pull requests

3 participants