Skip to content

Support optional fields in struct reflect in typescript #1988

@clearloop

Description

@clearloop

Motivation

Support optional fields in struct reflect in typescript, for example:

#[wasn_bindgen]
pub struct Ping {
    pong: Option<bool>,
}

in .d.ts

export class Ping {
    pong?: bool;
}

Proposed Solution

Struct generation in wasm_bindgen separate fields into getters and setters, and the ret_ty for getter or args for setter which decide the final field type out are embedded in JsBuilder, we can't checkout if some fields' types are optional, but...optional fields generate some special docs like @returns{{{}}} and @params{{{}}} we can trace.

If it is appropriate to render fields' types with checking if its doc contains .. | undefined ?

For example, we can change this line

https://github.com/rustwasm/wasm-bindgen/blob/f507a2a5ff2fa84d3197909a4b6f095e90ee4b98/crates/cli-support/src/js/mod.rs#L3070

if docs.contains("undefined") {
    *ty = "?".to_string() + ret_ty
} else {
    *ty = ret_ty.to_string()
}

and this line

https://github.com/rustwasm/wasm-bindgen/blob/f507a2a5ff2fa84d3197909a4b6f095e90ee4b98/crates/cli-support/src/js/mod.rs#L703

if &ty[0..1] == "?" {
    ts_dst.push_str("?: ");
    ts_dst.push_str(&ty[1..]);
} else {
    ts_dst.push_str(": ");
    ts_dst.push_str(&ty);
}

Alternatives

I think the solution above is quite a mess, but I can't figure out a better one.

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