#[derive(FromJSObj)]
{
// Attributes available to this derive:
#[rename]
#[js_default]
}
Expand description
Derive macro for implementing deserialization from JavaScript values to Rust structs.
This macro automatically implements the FromJSObj trait for a struct, allowing it
to be deserialized from JavaScript objects. Fields can be renamed using the rename
attribute to match different JavaScript property names.
§Attributes
rename = "name": Use a different name for the field in JavaScriptjs_default: UseDefault::default()if the field is missingjs_default = "value": Use a specific default value if the field is missing
§Field Types
- Required fields: Must exist in the JavaScript object, will error if missing
- Optional fields: Use
Option<T>type, will beNoneif missing - Fields with defaults: Use
#[js_default]or#[js_default = "value"], will use default if missing - All field types must implement
FromJSValue
§Example
ⓘ
#[derive(FromJSObj)]
struct Person {
#[rename = "firstName"]
first_name: String,
#[rename = "lastName"]
last_name: String,
age: i32,
// Optional field - will be None if missing
nickname: Option<String>,
// Field with default value
#[js_default = "active"]
status: String,
// Field using Default::default()
#[js_default]
score: i32,
}§JavaScript Usage
// This will successfully deserialize
const complete = {
firstName: "John",
lastName: "Doe",
age: 30,
nickname: "Johnny",
status: "premium"
};
// Result: Person { first_name: "John", last_name: "Doe", age: 30,
// nickname: Some("Johnny"), status: "premium", score: 0 }
// This will also work (using defaults)
const minimal = {
firstName: "Jane",
lastName: "Smith",
age: 25
};
// Result: Person { first_name: "Jane", last_name: "Smith", age: 25,
// nickname: None, status: "active", score: 0 }
// This will fail with clear error message
const incomplete = {
firstName: "John",
lastName: "Doe"
// Missing required field 'age'
};
// Error: "Required field 'age' is missing"§Error Handling
The macro provides detailed error messages:
- Missing required fields: “Required field ‘field_name’ is missing”
- Type conversion errors: “Failed to convert field ‘field_name’: [original error]”