### Generated TypeScript Definitions for Basic Example Source: https://github.com/madonoharu/tsify/blob/main/README.md This .d.ts file is automatically generated from the Rust code, defining the `Point` interface and the `into_js`/`from_js` functions. ```typescript /* tslint:disable */ /* eslint-disable */ /** * @returns {Point} */ export function into_js(): Point; /** * @param {Point} point */ export function from_js(point: Point): void; export interface Point { x: number; y: number; } ``` -------------------------------- ### Derive Tsify for Externally Tagged Enums Source: https://context7.com/madonoharu/tsify/llms.txt Enums are converted to TypeScript union types by default. This example shows an externally tagged enum, which is the default serde representation. ```rust use tsify::Tsify; // Externally tagged enum (default) #[derive(Tsify)] enum Message { Text(String), Image { url: String, width: u32, height: u32 }, Ping, } ``` -------------------------------- ### Rust: Field Renaming with Serde Source: https://context7.com/madonoharu/tsify/llms.txt Demonstrates how Tsify respects Serde's `#[serde(rename = "...")]` and `#[serde(rename_all = "...")]` attributes to transform Rust field names into their TypeScript equivalents. ```rust use tsify::Tsify; #[derive(Tsify)] #[serde(rename_all = "camelCase")] struct ApiRequest { /// Becomes "userId" user_id: String, /// Becomes "requestTime" request_time: u64, /// Becomes "pageSize" page_size: u32, } ``` ```rust #[derive(Tsify)] struct MixedRename { /// Individual field rename #[serde(rename = "ID")] id: String, /// Remains as-is name: String, /// Another custom rename #[serde(rename = "createdAt")] created_at: u64, } ``` -------------------------------- ### Optional Properties with Tsify and Serde Attributes Source: https://github.com/madonoharu/tsify/blob/main/README.md Define optional properties using `Option` and `#[tsify(optional)]` or `#[serde(skip_serializing_if = "Option::is_none")]` and `#[serde(default)]`. ```rust use tsify::Tsify; #[derive(Tsify)] struct Optional { #[tsify(optional)] a: Option, #[serde(skip_serializing_if = "Option::is_none")] b: Option, #[serde(default)] c: i32, } ``` -------------------------------- ### Configuring Serialization with Container Attributes Source: https://context7.com/madonoharu/tsify/llms.txt When using the `js` feature with `serde-wasm-bindgen`, configure serialization using container attributes like `missing_as_null`, `hashmap_as_object`, and `large_number_types_as_bigints` for optimized JavaScript interoperability. ```rust use std::collections::HashMap; use tsify::Tsify; use serde::Serialize; // Serialize HashMap as JavaScript object instead of Map #[derive(Tsify, Serialize)] #[tsify(hashmap_as_object)] struct Config { settings: HashMap, } // Serialize missing Optional fields as null instead of undefined #[derive(Tsify, Serialize)] #[tsify(missing_as_null)] struct Response { data: Option, } // Serialize i64/u64 as BigInt instead of Number #[derive(Tsify, Serialize)] #[tsify(large_number_types_as_bigints)] struct LargeNumbers { big_id: i64, timestamp: u64, } // With 'js' feature, HashMap generates: Map // With 'js' feature + hashmap_as_object: Record // With 'js' feature, i128 generates: bigint // With 'json' feature, i128 generates: number ``` -------------------------------- ### Cargo.toml Configuration for Tsify Source: https://context7.com/madonoharu/tsify/llms.txt Add Tsify to your `Cargo.toml` with appropriate feature flags. The `json` feature is default, while `js` is recommended for performance with native JavaScript values when using `serde-wasm-bindgen`. ```toml [dependencies] # Default (json feature) - uses serde_json for serialization tsify = "0.5.6" serde = { version = "1.0", features = ["derive"] } wasm-bindgen = "0.2" # Or with explicit json feature tsify = { version = "0.5.6", features = ["json"] } # Or with js feature for serde-wasm-bindgen (recommended for performance) tsify = { version = "0.5.6", default-features = false, features = ["js"] } [dev-dependencies] wasm-bindgen-test = "0.3" ``` -------------------------------- ### Rust Dependencies for Tsify and wasm-bindgen Source: https://github.com/madonoharu/tsify/blob/main/README.md Include tsify, serde, and wasm-bindgen in your Cargo.toml to enable TypeScript definition generation. ```toml [dependencies] tsify = "0.5.5" serde = { version = "1.0", features = ["derive"] } wasm-bindgen = { version = "0.2" } ``` -------------------------------- ### Basic Tsify Usage with wasm-bindgen Source: https://github.com/madonoharu/tsify/blob/main/README.md Define a Rust struct with `Tsify`, `Serialize`, and `Deserialize` derive macros. Use `into_ts()` and `to_rust()` with `Ts` for JS interop. ```rust use serde::{Deserialize, Serialize}; use tsify::Tsify; use tsify::Ts; use wasm_bindgen::prelude::*; use wasm_bindgen::JsError; #[derive(Tsify, Serialize, Deserialize)] pub struct Point { x: i32, y: i32, } #[wasm_bindgen] pub fn into_js() -> Result, JsError> { let point = Point { x: 0, y: 0 }; Ok(point.into_ts()?) } #[wasm_bindgen] pub fn from_js(point: Ts) -> Result<(), JsError> { let point: Point = point.to_rust()?; Ok(()) } ``` -------------------------------- ### Rust: Optional Properties Source: https://context7.com/madonoharu/tsify/llms.txt Shows how to mark struct fields as optional in TypeScript using `#[tsify(optional)]`, `#[serde(skip_serializing_if = "Option::is_none")]`, or `#[serde(default)]`. These result in TypeScript properties suffixed with `?`. ```rust use tsify::Tsify; #[derive(Tsify)] struct UserProfile { /// Required field username: String, /// Optional via tsify attribute #[tsify(optional)] display_name: Option, /// Optional via serde skip_serializing_if #[serde(skip_serializing_if = "Option::is_none")] bio: Option, /// Optional via serde default #[serde(default)] age: Option, /// Optional non-Option field with default #[serde(default)] verified: bool, } ``` -------------------------------- ### Rust: Apply Rotation Transformation Source: https://context7.com/madonoharu/tsify/llms.txt Deserializes a Vec2 from JavaScript, applies a rotation, and serializes the result back to JavaScript. Use `to_rust()` for deserialization and `into_ts()` for serialization. ```rust use tsify::{Tsify, Ts}; use serde::{Deserialize, Serialize}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsError; #[derive(Tsify, Serialize, Deserialize)] pub struct Vec2 { x: f64, y: f64, } #[derive(Tsify, Serialize, Deserialize)] pub struct Transform { scale: f64, rotation: f64, translation: Vec2, } /// Apply a rotation transformation to a vector #[wasm_bindgen] pub fn rotate(v: Ts, theta_rad: f64) -> Result, JsError> { // Deserialize from JavaScript - throws if invalid input let Vec2 { x, y } = v.to_rust()?; let cos = theta_rad.cos(); let sin = theta_rad.sin(); let result = Vec2 { x: x * cos - y * sin, y: x * sin + y * cos, }; // Serialize back to JavaScript Ok(result.into_ts()?) } ``` -------------------------------- ### Derive Tsify for Rust Structs Source: https://context7.com/madonoharu/tsify/llms.txt Use the `#[derive(Tsify)]` macro on Rust structs to automatically generate corresponding TypeScript interface definitions. This preserves doc comments as JSDoc annotations. ```rust use serde::{Deserialize, Serialize}; use tsify::Tsify; /// A 2D point in Cartesian coordinates #[derive(Tsify, Serialize, Deserialize)] pub struct Point { /// X coordinate x: f64, /// Y coordinate y: f64, } /// A rectangle defined by two points #[derive(Tsify, Serialize, Deserialize)] pub struct Rectangle { /// Top-left corner top_left: Point, /// Bottom-right corner bottom_right: Point, } ``` -------------------------------- ### Rust: Apply Full Transformation Source: https://context7.com/madonoharu/tsify/llms.txt Applies a scale, rotation, and translation transformation to a Vec2. It deserializes both the vector and transform from JavaScript and serializes the final transformed vector back. ```rust /// Apply a full transformation to a vector #[wasm_bindgen] pub fn apply_transform(v: Ts, transform: Ts) -> Result, JsError> { let v = v.to_rust()?; let t = transform.to_rust()?; // Scale let x = v.x * t.scale; let y = v.y * t.scale; // Rotate let cos = t.rotation.cos(); let sin = t.rotation.sin(); let x = x * cos - y * sin; let y = x * sin + y * cos; // Translate let result = Vec2 { x: x + t.translation.x, y: y + t.translation.y, }; Ok(result.into_ts()?) } ``` -------------------------------- ### Enum with Namespace using Tsify Source: https://github.com/madonoharu/tsify/blob/main/README.md Use `#[tsify(namespace)]` to generate a TypeScript namespace for enum variants, providing a more structured output. ```rust use tsify::Tsify; #[derive(Tsify)] #[tsify(namespace)] enum Color { Red, Blue, Green, Rgb(u8, u8, u8), Hsv { hue: f64, saturation: f64, value: f64, }, } ``` -------------------------------- ### Skipping Fields with Serde Attributes Source: https://context7.com/madonoharu/tsify/llms.txt Use `#[serde(skip)]`, `#[serde(skip_serializing)]`, or `#[serde(skip_deserializing)]` to exclude fields from TypeScript definitions. This is useful for internal state or server-only/client-only fields. ```rust use tsify::Tsify; #[derive(Tsify)] struct Document { /// Included in TypeScript id: String, /// Included in TypeScript content: String, /// Excluded - internal state #[serde(skip)] dirty: bool, /// Excluded - server-only field #[serde(skip_serializing)] internal_id: u64, /// Excluded - client-only field #[serde(skip_deserializing)] local_cache: bool, } // Generated TypeScript: // export interface Document { // id: string; // content: string; // } ``` -------------------------------- ### Define Rust Type Alias with Tsify Source: https://github.com/madonoharu/tsify/blob/main/README.md Use the `Tsify` derive macro and `declare` attribute to generate TypeScript type aliases from Rust structs and type aliases. Ensure the `tsify` crate is added as a dependency. ```rust use tsify::{declare, Tsify}; #[derive(Tsify)] struct Foo(T); #[declare] type Bar = Foo; ``` -------------------------------- ### Generating TypeScript Type Aliases with `#[declare]` Source: https://context7.com/madonoharu/tsify/llms.txt The `#[declare]` attribute macro generates TypeScript type aliases for Rust type aliases, including generic instantiations. This is useful for creating explicit type mappings. ```rust use tsify::{declare, Tsify}; #[derive(Tsify)] struct Response { data: T, status: u16, } #[derive(Tsify)] struct User { id: String, name: String, } #[derive(Tsify)] struct Product { id: String, price: f64, } #[declare] type UserResponse = Response; #[declare] type ProductResponse = Response; // Generated TypeScript: // export interface Response { // data: T; // status: number; // } // // export interface User { // id: string; // name: string; // } // // export interface Product { // id: string; // price: number; // } // // export type UserResponse = Response; // export type ProductResponse = Response; ``` -------------------------------- ### Derive Tsify for Adjacently Tagged Enums Source: https://context7.com/madonoharu/tsify/llms.txt Configure an adjacently tagged enum using `#[serde(tag = "kind", content = "data")]`. This generates a TypeScript union type with separate fields for the tag and the variant data. ```rust use tsify::Tsify; // Adjacently tagged enum #[derive(Tsify)] #[serde(tag = "kind", content = "data")] enum Response { Success(String), Error { code: i32, message: String }, } ``` -------------------------------- ### Generating TypeScript for Generic Types Source: https://context7.com/madonoharu/tsify/llms.txt Tsify supports Rust generic types, generating corresponding TypeScript generic interfaces and type aliases. This allows for type-safe generics across languages. ```rust use tsify::Tsify; #[derive(Tsify)] pub struct Container { value: T, count: u32, } #[derive(Tsify)] pub struct Pair { first: A, second: B, } #[derive(Tsify)] pub enum Result { Ok(T), Err(E), } #[derive(Tsify)] pub struct Wrapper(T); // Generated TypeScript: // export interface Container { // value: T; // count: number; // } // // export interface Pair { // first: A; // second: B; // } // // export type Result = { Ok: T } | { Err: E }; // // export type Wrapper = T; ``` -------------------------------- ### Generated TypeScript for Optional Properties Source: https://github.com/madonoharu/tsify/blob/main/README.md The generated TypeScript interface marks fields `a` and `b` as optional with `?`, and `c` is included due to `#[serde(default)]`. ```typescript export interface Optional { a?: number; b?: string; c?: number; } ``` -------------------------------- ### Flattening Nested Structs with `#[serde(flatten)]` Source: https://context7.com/madonoharu/tsify/llms.txt The `#[serde(flatten)]` attribute merges fields from a nested struct into the parent. This generates TypeScript interfaces that use `extends` when possible, promoting code reuse. ```rust use tsify::Tsify; #[derive(Tsify)] struct Metadata { created_at: u64, updated_at: u64, } #[derive(Tsify)] struct Auditable { created_by: String, modified_by: String, } #[derive(Tsify)] struct Document { id: String, title: String, #[serde(flatten)] metadata: Metadata, } // Generated TypeScript: // export interface Metadata { // created_at: number; // updated_at: number; // } // // export interface Document extends Metadata { // id: string; // title: string; // } ``` -------------------------------- ### Derive Tsify for Internally Tagged Enums Source: https://context7.com/madonoharu/tsify/llms.txt Use `#[serde(tag = "type")]` to define an internally tagged enum, which generates a TypeScript union type where each variant includes a common tag field. ```rust use tsify::Tsify; // Internally tagged enum #[derive(Tsify)] #[serde(tag = "type")] enum Event { Click { x: i32, y: i32 }, KeyPress { key: String }, Resize { width: u32, height: u32 }, } ``` -------------------------------- ### Generated TypeScript for Type Override Source: https://github.com/madonoharu/tsify/blob/main/README.md The generated TypeScript interface reflects the custom type specified for the `x` field. ```typescript export interface Foo { x: 0 | 1 | 2; } ``` -------------------------------- ### Generated TypeScript with Namespace for Enum Source: https://github.com/madonoharu/tsify/blob/main/README.md This output includes a `declare namespace Color` block, defining each enum variant as a type within that namespace, alongside the main union type. ```typescript declare namespace Color { export type Red = "Red"; export type Blue = "Blue"; export type Green = "Green"; export type Rgb = { Rgb: [number, number, number] }; export type Hsv = { Hsv: { hue: number; saturation: number; value: number }; }; } export type Color = | "Red" | "Blue" | "Green" | { Rgb: [number, number, number] } | { Hsv: { hue: number; saturation: number; value: number } }; ``` -------------------------------- ### Rust: Type Override Attribute Source: https://context7.com/madonoharu/tsify/llms.txt Demonstrates overriding generated TypeScript types for struct fields using the `#[tsify(type = "...")]` attribute. This allows for precise control over union types, template literal types, and custom type definitions. ```rust use tsify::Tsify; struct CustomType; // A type that doesn't implement Tsify #[derive(Tsify)] pub struct Config { /// Only allow 0, 1, or 2 #[tsify(type = "0 | 1 | 2")] log_level: i32, /// Template literal type for IDs #[tsify(type = "`user_${string}`")] user_id: String, /// Override with custom type #[tsify(type = "string | null")] optional_data: CustomType, /// Non-empty array type #[tsify(type = "[string, ...string[]]")] tags: Vec, } ``` -------------------------------- ### Derive Tsify for Untagged Enums Source: https://context7.com/madonoharu/tsify/llms.txt Use `#[serde(untagged)]` for untagged enums, which are converted directly to a TypeScript union type of the possible variant types. ```rust use tsify::Tsify; // Untagged enum #[derive(Tsify)] #[serde(untagged)] enum StringOrNumber { Str(String), Num(i32), } ``` -------------------------------- ### Enum Definition for Tsify Source: https://github.com/madonoharu/tsify/blob/main/README.md Define a Rust enum with `Tsify` derive. Variants can be unit, tuple, or struct types. ```rust use tsify::Tsify; #[derive(Tsify)] enum Color { Red, Blue, Green, Rgb(u8, u8, u8), Hsv { hue: f64, saturation: f64, value: f64, }, } ``` -------------------------------- ### Generated TypeScript Type Alias Source: https://github.com/madonoharu/tsify/blob/main/README.md The `#[declare]` attribute generates the corresponding TypeScript type definition. Generic types in Rust are mapped to generic types in TypeScript, and primitive types are converted accordingly (e.g., `i32` to `number`). ```typescript export type Foo = T; export type Bar = Foo; ``` -------------------------------- ### Type Override with Tsify Attribute Source: https://github.com/madonoharu/tsify/blob/main/README.md Use the `#[tsify(type = "...")]` attribute on a field to specify a custom TypeScript type, like a union of literals. ```rust use tsify::Tsify; #[derive(Tsify)] pub struct Foo { #[tsify(type = "0 | 1 | 2")] x: i32, } ``` -------------------------------- ### Generated TypeScript Type for Enum Source: https://github.com/madonoharu/tsify/blob/main/README.md The generated TypeScript type for the enum is a union of string literals for unit variants and object types for tuple/struct variants. ```typescript export type Color = | "Red" | "Blue" | "Green" | { Rgb: [number, number, number] } | { Hsv: { hue: number; saturation: number; value: number } }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.