FAQ - Help and questions

How do TypeScript interfaces and JSON map to Rust structs with serde?

#porting#typescript#serdepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A TypeScript interface becomes a struct that derives Serialize and Deserialize, optional fields become Option, string-literal unions become enums, and discriminated unions become enums with a serde tag attribute. Parsing checks the shape at the boundary and returns an error instead of undefined values later.

Checked with rustc 1.93.0, serde 1, serde_json 1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Add the crates serde (with the derive feature) and serde_json, derive Serialize and Deserialize on your types, and call serde_json::from_str. A document of the wrong shape returns an Err you handle at the edge of the program, where TypeScript would hand you a value that only looks typed.

TypeScriptRust with serde
interface User { id: number; name: string }struct User { id: u64, name: String }
email?: stringemail: Option<String> (add skip_serializing_if to omit it when writing)
role: "admin" | "member"enum Role { Admin, Member } with rename_all = "lowercase"
{ type: "click"; x: number } | { type: "key"; key: string }enum with #[serde(tag = "type")]
displayName in JSON, display_name in code#[serde(rename_all = "camelCase")]
Cargo.tomltoml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rsrust
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    email: Option<String>,
    role: Role,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Role {
    Admin,
    Member,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum Event {
    Click { x: i32, y: i32 },
    Key { key: String },
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
    display_name: String, // JSON key: "displayName"
}

fn main() -> Result<(), serde_json::Error> {
    let u: User = serde_json::from_str(r#"{"id": 7, "name": "Ada", "role": "admin"}"#)?;
    println!("{u:?}");
    println!("{}", serde_json::to_string(&u)?);

    let events: Vec<Event> = serde_json::from_str(r#"[{"type":"click","x":1,"y":2},{"type":"key","key":"Enter"}]"#)?;
    println!("{events:?}");
    println!("{}", serde_json::to_string(&events[0])?);

    let p: Profile = serde_json::from_str(r#"{"displayName": "Ada L."}"#)?;
    println!("{}", p.display_name);

    let bad = serde_json::from_str::<User>(r#"{"id": "seven", "name": "Ada", "role": "owner"}"#);
    println!("{}", bad.unwrap_err());
    Ok(())
}
text
User { id: 7, name: "Ada", email: None, role: Admin }
{"id":7,"name":"Ada","role":"admin"}
[Click { x: 1, y: 2 }, Key { key: "Enter" }]
{"type":"click","x":1,"y":2}
Ada L.
invalid type: string "seven", expected u64 at line 1 column 14

Common mistakes#

  • Using f64 for every number. Pick the integer type that matches the data; the error above is the point of the check.
  • Making every field Option to avoid parse errors. That moves the check to every place the field is used.
  • Forgetting #[serde(default)] on fields that older files do not have.

How do I accept JSON with fields I do not know?#

Unknown fields are ignored by default. Add #[serde(deny_unknown_fields)] to reject them, or a serde_json::Value field to keep them.

Can I share the types with a TypeScript front end?#

Crates that generate TypeScript types from Rust structs exist; check that the one you choose is maintained and matches your serde attributes.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet