导入的 extern Whatever; JavaScript 类型

T 参数&T 参数&mut T 参数T 返回值Option<T> 参数Option<T> 返回值JavaScript 表示
extern Whatever JavaScript 类/原型构造函数的实例

Rust 使用示例

#![allow(unused)]
fn main() {
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
#[derive(Copy, Clone, Debug)]
pub enum NumberEnum {
    Foo = 0,
    Bar = 1,
    Qux = 2,
}

#[wasm_bindgen]
#[derive(Copy, Clone, Debug)]
pub enum StringEnum {
    Foo = "foo",
    Bar = "bar",
    Qux = "qux",
}

#[wasm_bindgen]
pub struct Struct {
    pub number: NumberEnum,
    pub string: StringEnum,
}

#[wasm_bindgen]
extern "C" {
    pub type SomeJsType;
}

#[wasm_bindgen]
pub fn imported_type_by_value(x: SomeJsType) {
    /* ... */
}

#[wasm_bindgen]
pub fn imported_type_by_shared_ref(x: &SomeJsType) {
    /* ... */
}

#[wasm_bindgen]
pub fn return_imported_type() -> SomeJsType {
    unimplemented!()
}

#[wasm_bindgen]
pub fn take_option_imported_type(x: Option<SomeJsType>) {
    /* ... */
}

#[wasm_bindgen]
pub fn return_option_imported_type() -> Option<SomeJsType> {
    unimplemented!()
}
}

JavaScript 使用示例

import {
  imported_type_by_value,
  imported_type_by_shared_ref,
  return_imported_type,
  take_option_imported_type,
  return_option_imported_type,
} from './guide_supported_types_examples';

imported_type_by_value(new SomeJsType());
imported_type_by_shared_ref(new SomeJsType());

let x = return_imported_type();
console.log(x instanceof SomeJsType); // true

take_option_imported_type(null);
take_option_imported_type(undefined);
take_option_imported_type(new SomeJsType());

let y = return_option_imported_type();
if (y == null) {
  // ...
} else {
  console.log(y instanceof SomeJsType); // true
}