typescript - 使用额外的 `id` 属性将 Rust 结构展平回 TypeScript 单个对象,以返回 wasm-bindgen 函数

标签 typescript rust wasm-bindgen

我正在使用 wasm-bindgen 将数据从 Rust 代码传递到现有的 TypeScript 代码库。在我的 TypeScript 中,我有两个接口(interface),一个 InvoiceSchema 和一个 InvoiceWithId。唯一的区别是 InvoiceWithId 还有一个 id 属性。

interface InvoiceSchema { billTo: string, email: string }
interface InvoiceWithId extends InvoiceSchema { id: string }

据我了解,在 Rust 中,您不能从另一个结构继承并添加额外的 id 属性,因此我创建了一个结构:

struct InvoiceWithId {
  pub id: String
  pub schema: InvoiceSchema
}

在某些时候,我确实需要将其合并到现有 TypeScript 代码的单个对象中。

我应该如何转换这些对象并将其传递回 TypeScript,以便 id 属性成为基础对象的一部分?即

{ id: string, billTo: string, email: string }

最佳答案

您应该能够使用 serde-wasm-bindgen 箱来完成此操作,它允许您使用其 serde Serialize 实现将 Rust 结构序列化为 JavaScript 值。

#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct InvoiceSchema {
    pub bill_to: String,
    pub email: String,
}

#[derive(serde::Serialize)]
struct InvoiceWithId {
    pub id: String,
    #[serde(flatten)]
    pub schema: InvoiceSchema,
}

#[wasm_bindgen]
fn get_invoice_with_id() -> JsValue {
    let invoice_with_id = InvoiceWithId { ... };

    serde_wasm_bindgen::to_value(&invoice_with_id).unwrap()
}

关于typescript - 使用额外的 `id` 属性将 Rust 结构展平回 TypeScript 单个对象,以返回 wasm-bindgen 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77205904/

相关文章:

rust - 如何将HashSet <&String>转换为HashSet <String>

error-handling - 结果错误时从函数返回默认值

rust - 如何使 Rust Game of Life WebAssembly 作为静态网站工作?

javascript - Angular 5 太多地理位置响应

compiler-construction - TypeScript 编译错误 TS5037 : Cannot compile external modules unless the '--module' flag is provided

rust - 具有包含异步 block 的闭包的异步方法无法推断适当的生存期

Rust Wasm Bindgen 返回对象但获取一个数字

rust - 如何在WASM-Bindgen和Rust中实际获取响应正文的文本

javascript - Typescript 中的工厂函数语法

.NET Core 项目中的 Angular 12 - 路由不工作