我正在使用wasm-bindgen将数据从RUST代码传递到现有的打字代码库.在我的Typescript 中,我有两个界面,一个是InvoiceSchema,一个是InvoiceWithId.唯一的区别是InvoiceWithId也有id属性.

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

我知道在Rust中,您不能继承另一个 struct 并添加额外的id属性,因此我创建了一个 struct :

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

在某种程度上,我确实需要将其合并到现有打字代码的单个对象中.

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

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

推荐答案

您应该能够使用serde-wasm-bindgen箱来实现这一点,它允许您使用它们的serde Serialize实现将Rust struct 序列化为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相关问答推荐

动态判断TypScript对象是否具有不带自定义类型保护的键

找不到带名称的管道''

有没有一种方法可以在保持类型的可选状态的同时更改类型?

如果存在ts—mock—imports,我们是否需要typescpt中的IoC容器

在泛型类型中对子代执行递归时出错

如何正确地对类型脚本泛型进行限制

Vue SFC中的多个脚本块共享导入的符号

如何按不能保证的功能过滤按键?

仅针对某些状态代码重试HTTP请求

在排版修饰器中推断方法响应类型

如何编写在返回函数上分配了属性的类型安全泛型闭包

笛卡尔产品类型

有没有一种方法可以确保类型的成员实际存在于TypeScript中的对象中?

是否有可能避免此泛型函数体中的类型断言?

抽象类对派生类强制不同的构造函数签名

打字错误TS2305:模块常量没有导出的成员

为什么数字是`{[key:string]:UNKNOWN;}`的有效密钥?

如何键入';v型';

在对象类型的类型别名中,属性是用分号 (;) 还是逗号 (,) 分隔的?

如何从 Select 元素中删除选项