我正在使用 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/