Skip to main content

ts_function

Attribute Macro ts_function 

Source
#[ts_function]
Expand description

Generates TypeScript type aliases and wasm-bindgen ABI trait implementations for Rust callback wrapper structs.

ts-function acts as a bridge for function/callback types in pure Rust when interoperating with TypeScript using ts-macro. It can be applied to either type aliases (pub type MyCb = fn(args: ...)) or impl blocks (the “escape hatch”).

§Examples

Basic Usage

use ts_function::{ts, ts_function};

#[ts_function]
pub type OnReadyCb = fn(msg: String);

#[ts]
struct AppCallbacks {
    on_ready: OnReadyCb,
}

Escape Hatch Usage

For completely custom serialization or embedding specific side-effects and error handling directly into the callback execution:

use wasm_bindgen::prelude::*;
use ts_function::ts_function;

pub struct CustomLoggingCallback(pub js_sys::Function);

#[ts_function]
impl CustomLoggingCallback {
    pub fn call(&self, val: f64) {
        // Call the JS function and handle errors internally
        let _ = self.0.call1(
            &wasm_bindgen::JsValue::NULL,
            &wasm_bindgen::JsValue::from_f64(val),
        );
    }
}