Skip to content

Setting Typescript types for returned duck-typed objects. #1591

@andreubotella

Description

@andreubotella

Motivation

As far as I understand, the only way to return an object with a duck-typed interface from Rust to JS for the time being is to build it by reflection and return it as a JsValue. The generated Typescript definition rightfully gives the returned type as any, which does its job, but it fails to convey the author's intentions. A better solution would be to add a way to declare a Typescript type for a returned JsValue.

Proposed Solution

The proposed solution would be to add a wasm_bindgen attribute, perhaps called something like return_typescript_type, containing a Typescript type. Any named references contained in the type must be defined elsewhere in a typescript_custom_section, although parsing the TS to ensure that might not be a priority.

#[wasm_bindgen(js_name = jpegImageSize, return_typescript_type = {width: number, height: number}]
pub fn jpeg_image_size(image: &[u8]) -> JsValue {
   let (width, height): (u32, u32) = unimplemented!();
   let ret = Object::new();
   Reflect::set(&ret, &JsValue::from_str("width"), &JsValue::from_f64(width as f64);
   Reflect::set(&ret, &JsValue::from_str("height"), &JsValue::from_f64(height as f64);
   ret
}

Alternatives

Hopefully sometime in the future, wasm_bindgen will offer a way to return duck-typed interfaces from Rust without reflection, which would provide the necessary types for the TS declaration to be reasonably complete by default.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions