### Install cargo-readme Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Install the cargo-readme tool to generate documentation. ```shell cargo install cargo-readme ``` -------------------------------- ### Configuration Priority Examples Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Examples showing how large integer configuration is defined across different priority levels. ```rust Config::new().with_large_int("number") ``` ```bash export TS_RS_LARGE_INT="number" ``` ```toml [env] TS_RS_LARGE_INT = "number" ``` ```rust // Export dir: "./bindings" // Large int: "bigint" // Import extension: None ``` -------------------------------- ### Configure valid import extensions Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Examples of valid and invalid configurations for import extensions. ```rust // Valid let cfg = Config::new() .with_import_extension(Some("js")); // OK let cfg = Config::new() .with_import_extension(Some("ts")); // OK let cfg = Config::new() .with_import_extension(None); // OK // Invalid (though compiler won't catch this) let cfg = Config::new() .with_import_extension(Some("jsx")); // Will fail at runtime during export ``` -------------------------------- ### Basic configuration setup Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Initializes a new configuration with a custom output directory for generated TypeScript files. ```rust use ts_rs::{Config, TS}; // Create config with custom output directory let cfg = Config::new() .with_out_dir("./generated/ts"); // Export a type User::export_all(&cfg)?; ``` -------------------------------- ### Access output_path field Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Examples showing default and custom export paths for a dependency. ```rust // Default export path dep.output_path == PathBuf::from("User.ts") // Custom export path dep.output_path == PathBuf::from("types/models/User.ts") ``` -------------------------------- ### Implement a custom TypeVisitor Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md Example implementation of a visitor that prints the name of each visited type. ```rust struct MyVisitor; impl TypeVisitor for MyVisitor { fn visit(&mut self) { println!("Visiting: {}", std::any::type_name::()); } } let mut visitor = MyVisitor; User::visit_dependencies(&mut visitor); // Prints the name of each field type ``` -------------------------------- ### Format doc comments with format_docs Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/types.md Examples showing how to use format_docs with empty, single-line, and multi-line inputs. ```rust use ts_rs::format_docs; // No docs let result = format_docs(&[]); assert_eq!(result, ""); // Single line docs let result = format_docs(&[" A user account"]); // Output: "/** A user account */\n" // Multi-line docs let result = format_docs(&[" First line", " Second line"]); // Output: "/**\n * First line\n * Second line\n */\n" ``` -------------------------------- ### Formatting Variant Handling Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Example of handling formatting errors during export. ```rust #[cfg(feature = "format")] use ts_rs::ExportError; // This would only occur with malformed generated code, which is unlikely // It indicates a bug in ts-rs type generation let result = User::export_to_string(&cfg); match result { #[cfg(feature = "format")] Err(ExportError::Formatting(msg)) => { eprintln!("Formatting failed: {}", msg); } Ok(code) => println!("Export successful: {}", code.len()), Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Debug Macro Expansion Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Commands to install and run cargo-expand to inspect generated macro code. ```bash cargo install cargo-expand cargo expand --lib ``` -------------------------------- ### CannotBeExported Usage and Handling Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Examples for triggering and handling the CannotBeExported error. ```rust use ts_rs::{TS, Config}; let cfg = Config::new(); match i32::export(&cfg) { Err(ts_rs::ExportError::CannotBeExported(type_name)) => { eprintln!("Cannot export: {}", type_name); // Cannot export: i32 } Ok(_) => {} } ``` ```rust use ts_rs::ExportError; match type_result { Err(ExportError::CannotBeExported(_)) => { // Type is not exportable, skip it println!("Skipping non-exportable type"); } Ok(_) => println!("Export successful"), Err(e) => eprintln!("Export failed: {}", e), } ``` -------------------------------- ### Handle Fmt error Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Example of catching the Fmt error during string exportation. ```rust use ts_rs::{TS, Config, ExportError}; match User::export_to_string(&cfg) { Err(ExportError::Fmt(_)) => { eprintln!("Internal formatting error (very rare)"); } Ok(code) => println!("Export successful: {} bytes", code.len()), Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Invoke visit_generics Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md Example of calling visit_generics on a Vec type. ```rust let mut visitor = MyVisitor; Vec::::visit_generics(&mut visitor); // Calls visitor.visit::() ``` -------------------------------- ### Correct usage of optional field Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/types.md Example of the correct implementation using Option with the #[ts(optional)] attribute. ```rust #[derive(TS)] struct User { #[ts(optional)] nickname: Option, // OK: is Option } ``` -------------------------------- ### Io Variant Handling and Conversion Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Examples for handling IO errors and automatic conversion from std::io::Error. ```rust use ts_rs::{TS, Config, ExportError}; use std::io; let cfg = Config::new() .with_out_dir("/nonexistent/path"); match User::export_all(&cfg) { Err(ExportError::Io(io_error)) => { match io_error.kind() { io::ErrorKind::PermissionDenied => { eprintln!("Permission denied: {}", io_error); } io::ErrorKind::NotFound => { eprintln!("Directory not found: {}", io_error); } _ => eprintln!("IO error: {}", io_error), } } Ok(_) => println!("Export successful"), Err(e) => eprintln!("Other error: {}", e), } ``` ```rust // io::Error is automatically converted to ExportError::Io fn create_file() -> Result<(), ExportError> { std::fs::create_dir_all("./bindings")?; // Converts io::Error to ExportError Ok(()) } ``` -------------------------------- ### Track generic parameters Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Example of how the macro identifies unused generic parameters in a struct. ```rust #[derive(TS)] struct Container { value: T, // U is not used } // Generates warning or note that U is unused ``` -------------------------------- ### TS Derive Macro Usage Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Example of applying the TS derive macro alongside standard Rust derives. ```rust #[derive(Debug, Clone, Serialize, TS)] struct User { id: i32, name: String, } // All derives are applied independently ``` -------------------------------- ### Simple Struct Definition and Generated Implementation Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Example of a simple struct marked for export and the corresponding generated TS trait implementation. ```rust #[derive(TS)] #[ts(export)] struct User { id: i32, name: String, } ``` ```rust impl TS for User { type WithoutGenerics = User; type OptionInnerType = Self; fn name(cfg: &Config) -> String { "User".to_string() } fn inline(cfg: &Config) -> String { format!( "{{ id: {}, name: {} }}", ::inline(cfg), ::inline(cfg), ) } fn decl(cfg: &Config) -> String { format!( "type User = {{ id: {}, name: {} }};", ::name(cfg), ::name(cfg), ) } fn visit_dependencies(v: &mut impl TypeVisitor) where Self: 'static, { // No external dependencies for primitives } fn output_path() -> Option { Some(PathBuf::from("User.ts")) } } #[cfg(test)] mod ts_bindings { #[test] fn export_user_ts() { let cfg = ts_rs::Config::from_env(); User::export_all(&cfg).expect("Failed to export User"); } } ``` -------------------------------- ### Valid crate feature combinations Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Examples of enabling multiple independent features within the ts-rs dependency declaration. ```toml # All valid combinations ts-rs = { version = "12.0", features = ["uuid-impl"] } ts-rs = { version = "12.0", features = ["uuid-impl", "chrono-impl"] } ts-rs = { version = "12.0", features = ["uuid-impl", "chrono-impl", "format"] } ``` -------------------------------- ### Implement Dummy in a generic struct Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/types.md Example showing how to replace generic parameters with the Dummy type in the WithoutGenerics associated type. ```rust struct Point(T); impl TS for Point { type WithoutGenerics = Point; // ... } ``` -------------------------------- ### Derive TS macro usage with doc comments Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/types.md Example of how the derive macro automatically utilizes doc comments for TypeScript generation. ```rust /// This is a user #[derive(TS)] struct User { } // Generated JSDoc: // /** // * This is a user // */ // export type User = { ... }; ``` -------------------------------- ### Build the project Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Build the project using Cargo. ```shell cargo build ``` -------------------------------- ### Set up pre-commit hook for formatting Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Create a pre-commit hook to automatically format code using `cargo +nightly fmt` before each commit. This requires the nightly toolchain. ```shell #!/bin/sh cargo +nightly fmt ``` -------------------------------- ### Run the test suite Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Execute the project's test suite. ```shell cargo test ``` -------------------------------- ### Handle InvalidImportExtension error Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Example of catching the InvalidImportExtension error when an invalid extension is provided. ```rust use ts_rs::{TS, Config, ExportError}; use std::env; env::set_var("TS_RS_IMPORT_EXTENSION", "mjs"); // Invalid! let cfg = Config::from_env(); match User::export_all(&cfg) { Err(ExportError::InvalidImportExtension) => { eprintln!("Use TS_RS_IMPORT_EXTENSION=js or TS_RS_IMPORT_EXTENSION=ts"); } Ok(_) => println!("Export successful"), Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Load configuration from environment Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Initializes the configuration object using settings defined in environment variables. ```rust // Load all settings from environment variables let cfg = Config::from_env(); MyType::export_all(&cfg)?; ``` -------------------------------- ### Initialize Config with Default Values Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Creates a new configuration instance and demonstrates chaining the with_out_dir method to override the default export directory. ```rust let cfg = Config::new() .with_out_dir("./ts"); ``` -------------------------------- ### Apply fine-grained configuration options Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Demonstrates chaining multiple configuration methods to control output directory, integer handling, import extensions, and array limits. ```rust let cfg = Config::new() .with_out_dir("./bindings") .with_large_int("bigint") .with_import_extension(Some("js")) .with_array_tuple_limit(32); User::export_all(&cfg)?; // Large arrays become Array, imports include .js extension ``` -------------------------------- ### Access ts_name field Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Examples of accessing the TypeScript name for standard and generic types. ```rust // For a User struct dep.ts_name == "User" // For a generic type dep.ts_name == "Point" // Without generics ``` -------------------------------- ### Initialize Config from Environment Variables Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Creates a configuration instance populated by environment variables, which can be defined in a .cargo/config.toml file. ```rust // .cargo/config.toml: // [env] // TS_RS_EXPORT_DIR = { value = "bindings", relative = true } // TS_RS_LARGE_INT = "number" let cfg = Config::from_env(); // Reads TS_RS_EXPORT_DIR and TS_RS_LARGE_INT from environment ``` -------------------------------- ### Handle ManifestDirNotSet error Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Example of catching the ManifestDirNotSet error when running outside of a Cargo context. ```rust use ts_rs::{TS, Config, ExportError}; let cfg = Config::from_env(); match User::export_all(&cfg) { Err(ExportError::ManifestDirNotSet) => { eprintln!("Must run this code from cargo (cargo test, cargo run, etc.)"); } Ok(_) => println!("Export successful"), Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Configure via .cargo/config.toml Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Define project-wide configuration in the .cargo/config.toml file to persist settings. ```toml # /.cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "bindings", relative = true } TS_RS_LARGE_INT = "bigint" TS_RS_IMPORT_EXTENSION = "js" TS_RS_USE_V11_HASHMAP = "false" ``` -------------------------------- ### visit_dependencies(&mut impl TypeVisitor) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Iterates over all type dependencies and records them using the provided visitor. ```APIDOC ## visit_dependencies(&mut impl TypeVisitor) ### Description Iterates over all type dependencies and calls visitor.visit::() for each dependency. The derived macro automatically implements this by visiting all field types. ### Parameters - **visitor** (&mut impl TypeVisitor) - Required - Visitor instance to record dependencies ``` -------------------------------- ### Build an ordered export list Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md Uses a BTreeSet to collect and sort dependencies automatically. ```rust use ts_rs::{TS, TypeVisitor, Config, Dependency}; use std::collections::BTreeSet; struct SortedCollector<'a> { cfg: &'a Config, sorted_deps: BTreeSet, } impl<'a> TypeVisitor for SortedCollector<'a> { fn visit(&mut self) { if let Some(dep) = Dependency::from_ty::(self.cfg) { self.sorted_deps.insert(dep); } } } let cfg = Config::new(); let mut visitor = SortedCollector { cfg: &cfg, sorted_deps: BTreeSet::new(), }; User::visit_dependencies(&mut visitor); // Dependencies are now sorted by type_id, ts_name, and output_path for dep in visitor.sorted_deps { println!("Export {} to {}", dep.ts_name, dep.output_path.display()); } ``` -------------------------------- ### Exporting Structs with TS_RS_EXPORT_DIR Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of how the export directory setting influences the generated TypeScript file location. ```rust // With TS_RS_EXPORT_DIR = "bindings" #[derive(TS)] #[ts(export)] struct User { } // Exports to: ./bindings/User.ts // With TS_RS_EXPORT_DIR = "src/types" // Exports to: ./src/types/User.ts ``` -------------------------------- ### Generate README.md on Windows Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Run this command in the ts-rs directory to generate the README.md file on Windows. ```shell cargo readme -o ..\README.md ``` -------------------------------- ### Workspace-level Configuration Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Apply configuration settings at the workspace root level using the .cargo/config.toml file. ```toml # /.cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "crates/bindings", relative = true } TS_RS_LARGE_INT = "bigint" ``` -------------------------------- ### Compare formatting output in Rust Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Demonstrates the difference in output when the format feature is enabled versus disabled. ```rust // With format feature let cfg = Config::new(); let ts_code = User::export_to_string(&cfg)?; // Output is automatically formatted (indented, etc.) // Without format feature let ts_code = User::export_to_string(&cfg)?; // Output is compact, minimal whitespace ``` -------------------------------- ### Custom Configuration Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Configure export settings such as output directory, large integer handling, and import extensions. ```rust use ts_rs::Config; fn export_with_config() -> Result<(), Box> { let cfg = Config::new() .with_out_dir("./src/types/generated") .with_large_int("bigint") .with_import_extension(Some("js")) .with_array_tuple_limit(50); MyApi::export_all(&cfg)?; Ok(()) } ``` -------------------------------- ### Implement visit_dependencies for dependency tracking Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Iterates over type dependencies and records them using the provided visitor. Automatically implemented by the derived macro. ```rust fn visit_dependencies(_: &mut impl TypeVisitor) where Self: 'static, { } ``` ```rust // For User struct with fields: user_id: i32, name: String, role: Role // This would visit i32, String, and Role types User::visit_dependencies(&mut visitor); ``` -------------------------------- ### Methods Source: https://github.com/aleph-alpha/ts-rs/wiki/Manually-implementing-the-TS-trait Documentation for various methods available. ```APIDOC ## Methods ### ident Retrieves the identifier. ### get_export_to Gets the export destination. ### decl Declares a type or item. ### decl_concrete Declares a concrete type or item. ### name Returns the name of the item. ### inline Inlines a representation of the item. ### inline_flattened Inlines a flattened representation of the item. ### dependency_types Retrieves the dependency types. ### dependencies Retrieves the dependencies. ### export Exports the item. ### export_to Exports the item to a specific destination. ### export_to_string Exports the item as a string. ``` -------------------------------- ### Configure Environment Variables for Projects Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Set these environment variables in your project configuration to control export directories, large integer handling, and import extensions. ```toml [env] TS_RS_EXPORT_DIR = { value = "src/types", relative = true } TS_RS_LARGE_INT = "bigint" TS_RS_IMPORT_EXTENSION = "ts" ``` ```toml [env] TS_RS_EXPORT_DIR = { value = "dist/types", relative = true } TS_RS_LARGE_INT = "bigint" TS_RS_IMPORT_EXTENSION = "js" ``` ```toml [env] TS_RS_EXPORT_DIR = { value = "client/src/generated", relative = true } TS_RS_LARGE_INT = "bigint" TS_RS_IMPORT_EXTENSION = "ts" ``` ```toml [env] TS_RS_EXPORT_DIR = { value = "bindings", relative = true } TS_RS_LARGE_INT = "number" TS_RS_IMPORT_EXTENSION = "" ``` -------------------------------- ### Configure Export Settings Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Configure output directories and type mappings using cargo configuration or environment variables. ```toml [env] TS_RS_EXPORT_DIR = { value = "src/generated", relative = true } TS_RS_LARGE_INT = "bigint" TS_RS_IMPORT_EXTENSION = "js" ``` ```bash export TS_RS_EXPORT_DIR="./types" export TS_RS_LARGE_INT="bigint" cargo test ``` -------------------------------- ### Generic Struct Definition and Generated Implementation Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Example of a generic struct and the corresponding generated TS trait implementation handling type visitors. ```rust #[derive(TS)] struct Box { content: T, } ``` ```rust impl TS for Box { type WithoutGenerics = Box; type OptionInnerType = Self; fn name(cfg: &Config) -> String { format!("Box<{}>", ::name(cfg)) } fn visit_dependencies(v: &mut impl TypeVisitor) where Self: 'static, { v.visit::(); } fn visit_generics(v: &mut impl TypeVisitor) where Self: 'static, { ::visit_generics(v); v.visit::(); } } ``` -------------------------------- ### Implement docs() Method Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Returns JSDoc comments for the type, automatically populated from Rust doc attributes. ```rust fn docs() -> Option { None } ``` ```rust /// A user account with associated metadata #[derive(TS)] struct User { id: i32, name: String, } // docs() returns: "/** A user account with associated metadata */\n" ``` -------------------------------- ### Configure output directory Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Defines the base directory for exporting generated TypeScript bindings. ```rust let cfg = Config::new() .with_out_dir("./src/generated"); User::export_all(&cfg)?; // Writes to ./src/generated/User.ts ``` ```rust let cfg = Config::new().with_out_dir("./bindings"); assert_eq!(cfg.out_dir(), Path::new("./bindings")); ``` -------------------------------- ### Usage of Dependency::from_ty Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Demonstrates how to resolve dependencies for exportable types versus primitives or internal types. ```rust use ts_rs::{TS, Config, Dependency}; let cfg = Config::new(); // Exportable types return Some let dep = Dependency::from_ty::(&cfg); assert!(dep.is_some()); // Primitive types return None let dep = Dependency::from_ty::(&cfg); assert!(dep.is_none()); // Unexcluded types return None let dep = Dependency::from_ty::(&cfg); assert!(dep.is_none()); ``` -------------------------------- ### Generate README.md on other systems Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Run this command in the ts-rs directory to generate the README.md file on non-Windows systems. ```shell cargo readme > ../README.md ``` -------------------------------- ### Configure TS_RS_IMPORT_EXTENSION Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Setting the import extension via .cargo/config.toml. ```toml # .cargo/config.toml [env] TS_RS_IMPORT_EXTENSION = "js" ``` -------------------------------- ### Enable Macro Backtrace Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Command to capture detailed macro error information during build. ```bash RUST_BACKTRACE=1 cargo build 2>&1 | head -50 ``` -------------------------------- ### Visualize Documentation Relationships Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/MANIFEST.md A visual map showing the hierarchy and connections between various documentation files in the project. ```text README.md (start here) ↓ INDEX.md (navigate) ├─→ api-reference-*.md (4 documents) ├─→ configuration.md + feature-flags.md ├─→ types.md + errors.md ├─→ derive-macro-attributes.md ├─→ macro-system.md └─→ usage-examples.md ``` -------------------------------- ### Generate Bindings in Build Script Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Automate binding generation during the build process using a build.rs script. ```rust // build.rs use ts_rs::Config; fn main() { let cfg = Config::from_env() .with_out_dir("./generated/types"); my_lib::export_all_types(&cfg) .expect("Failed to generate TypeScript bindings"); } ``` -------------------------------- ### Implement the visit method Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md The signature for the visit method used to process types during traversal. ```rust fn visit(&mut self); ``` -------------------------------- ### export_all(cfg: &Config) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Exports the type and all of its transitive dependencies recursively. This is the recommended method for generating complete type graphs. ```APIDOC ## export_all(cfg: &Config) ### Description Exports this type and all of its transitive dependencies. Recursively exports each dependency to its designated output file. ### Parameters - **cfg** (&Config) - Required - TypeScript generation configuration with export directory ### Returns - **Result<(), ExportError>** - Ok(()) on success or ExportError on failure. ``` -------------------------------- ### Enable astrolabe support Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Enables support for astrolabe astronomical types. ```toml [dependencies] ts-rs = { version = "12.0", features = ["astrolabe-impl"] } astrolabe = "0.5" ``` -------------------------------- ### Collect dependencies for a type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Retrieves all direct dependencies for a specific type using the provided configuration. ```rust use ts_rs::{TS, Config, Dependency}; let cfg = Config::new(); // Get all direct dependencies of a type let deps = User::dependencies(&cfg); for dep in deps { println!("Depends on: {}", dep.ts_name); println!("Exported to: {}", dep.output_path.display()); } ``` -------------------------------- ### with_out_dir(dir: impl Into) -> Self Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Sets the base directory where TypeScript bindings will be exported. ```APIDOC ## with_out_dir(dir: impl Into) -> Self ### Description Sets the base directory where TypeScript bindings will be exported. Affects TS::export(), TS::export_all(), and automatic export of types with #[ts(export)]. ### Parameters - **dir** (impl Into) - Required - Output directory path ### Returns Modified Config for method chaining. ``` -------------------------------- ### Walk field types Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Illustrates how the macro generates visitor code for field types to track dependencies. ```rust #[derive(TS)] struct User { id: i32, profile: Profile, posts: Vec, } // Generated walk code: fn visit_dependencies(v: &mut impl TypeVisitor) { v.visit::(); v.visit::(); v.visit::>(); } ``` -------------------------------- ### Implement semver::Version Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Use the semver-impl feature to map Version types to TypeScript strings. ```rust use semver::Version; #[derive(TS)] #[ts(export)] struct Package { version: Version, } // Generated: type Package = { version: string }; ``` ```toml [dependencies] ts-rs = { version = "12.0", features = ["semver-impl"] } semver = "1" ``` -------------------------------- ### Implement url::Url Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Use the url-impl feature to map Url types to TypeScript strings. ```rust use url::Url; #[derive(TS)] #[ts(export)] struct Link { href: Url, } // Generated: type Link = { href: string }; ``` ```toml [dependencies] ts-rs = { version = "12.0", features = ["url-impl"] } url = "2" ``` -------------------------------- ### visit_generics(&mut impl TypeVisitor) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Iterates over all generic type parameters and records them using the provided visitor. ```APIDOC ## visit_generics(&mut impl TypeVisitor) ### Description Iterates over all generic type parameters and calls visitor.visit::() for each. This is used during dependency resolution to identify types used as generics. ### Parameters - **visitor** (&mut impl TypeVisitor) - Required - Visitor instance to record generics ``` -------------------------------- ### Define custom export paths Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Demonstrates using the export_to attribute to specify a custom file path for generated bindings. ```rust #[ts(export, export_to = "models/User.ts")] struct User { } // Generated test still calls export_all(), but output_path() // returns the custom path ``` -------------------------------- ### Constants Source: https://github.com/aleph-alpha/ts-rs/wiki/Manually-implementing-the-TS-trait Information on available constants. ```APIDOC ## Constants ### EXPORT_TO Represents the export destination. ### DOCS Related to documentation generation or retrieval. ``` -------------------------------- ### Configure import file extensions Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Sets the file extension used in generated import statements. ```rust let cfg = Config::new() .with_import_extension(Some("js")); // Generated import statements will include .js extension ``` ```rust let cfg = Config::new() .with_import_extension(Some("ts")); assert_eq!(cfg.import_extension(), Some("ts")); ``` -------------------------------- ### Integrate ts-rs in build.rs Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Use this snippet in your build.rs file to configure the output directory and trigger TypeScript binding generation during the build process. ```rust // build.rs use ts_rs::Config; fn main() { let cfg = Config::from_env() .with_out_dir("./generated"); my_types::MyType::export_all(&cfg) .expect("Failed to generate TypeScript bindings"); println!("cargo:rerun-if-env-changed=TS_RS_EXPORT_DIR"); println!("cargo:rerun-if-env-changed=TS_RS_LARGE_INT"); println!("cargo:rerun-if-env-changed=TS_RS_IMPORT_EXTENSION"); } ``` -------------------------------- ### Integrate with build.rs Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Configures type exports to run automatically during the build process using a build script. ```rust // build.rs use ts_rs::Config; fn main() { let cfg = Config::from_env() .with_out_dir("./src/types"); // Export types during build my_crate::MyType::export_all(&cfg) .expect("Failed to export TypeScript bindings"); } ``` -------------------------------- ### Migrate TS_RS_USE_V11_HASHMAP Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Configuration and code markers for migrating away from v11 HashMap behavior. ```toml # During migration from v11 [env] TS_RS_USE_V11_HASHMAP = "true" # Temporarily enable for v11 behavior ``` ```rust // Mark the usage as deprecated to remind yourself to fix it #[deprecated = "remove after migration to v12 style hashmap handling"] struct OldStyleMap { data: HashMap, } ``` -------------------------------- ### Define generic API response wrappers Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Create generic structs to standardize API responses across the application. ```rust use ts_rs::TS; use serde::Serialize; #[derive(Serialize, TS)] #[ts(export)] struct ApiResponse { success: bool, data: Option, error: Option, timestamp: String, } #[derive(Serialize, TS)] #[ts(export)] struct User { id: i32, name: String, } // Generated: // export type ApiResponse = { ... }; // export type User = { id: number, name: string }; // // TypeScript usage: // type UserResponse = ApiResponse; ``` -------------------------------- ### Define TS::visit_dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md The default implementation for visiting direct dependencies of a type. ```rust fn visit_dependencies(_: &mut impl TypeVisitor) where Self: 'static, { } ``` -------------------------------- ### Configure v11 hashmap behavior Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Enables legacy v11 hashmap behavior where keys are optional. This is deprecated and intended only for migration assistance. ```rust #[deprecated = "this option is merely meant to aid migration to v12 and will be removed in a future release"] pub fn with_v11_hashmap(mut self) -> Self ``` ```rust #[allow(deprecated)] let cfg = Config::new() .with_v11_hashmap(); ``` -------------------------------- ### Triggering Exports via CLI Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Commands to execute tests and trigger the export process using environment variables. ```bash # Uses TS_RS_EXPORT_DIR and other env vars from .cargo/config.toml or shell cargo test --lib # Or with explicit environment variables TS_RS_EXPORT_DIR=./src/types TS_RS_LARGE_INT=number cargo test --lib ``` -------------------------------- ### Enable no-serde-warnings feature Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Add this to your Cargo.toml to suppress compile-time warnings for unsupported serde attributes. ```toml [dependencies] ts-rs = { version = "12.0", features = ["no-serde-warnings"] } ``` -------------------------------- ### export_to_string(cfg: &Config) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Generates TypeScript bindings as a string without writing to the filesystem. ```APIDOC ## export_to_string(cfg: &Config) ### Description Generates bindings without writing to disk. Useful for testing, programmatic generation, or custom output handling. ### Parameters - **cfg** (&Config) - Required - TypeScript generation configuration ### Returns - **Result** - Generated TypeScript bindings as a string. ``` -------------------------------- ### export(cfg: &Config) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Exports a single type to the filesystem without its dependencies. The output path is determined by the ts(export_to) attribute or defaults to .ts. ```APIDOC ## export(cfg: &Config) ### Description Exports only this type to the filesystem, without its dependencies. The output path is determined by #[ts(export_to = "...")] or defaults to .ts. ### Parameters - **cfg** (&Config) - Required - TypeScript generation configuration with export directory ### Returns - **Result<(), ExportError>** - Ok(()) on success or ExportError on failure. ``` -------------------------------- ### Collect type dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md A standard implementation of TypeVisitor to gather dependencies into a vector. ```rust use ts_rs::{TS, TypeVisitor, Config, Dependency}; use std::collections::Vec; struct DependencyCollector<'a> { cfg: &'a Config, dependencies: Vec, } impl<'a> TypeVisitor for DependencyCollector<'a> { fn visit(&mut self) { if let Some(dep) = Dependency::from_ty::(self.cfg) { self.dependencies.push(dep); } } } // Usage let cfg = Config::new(); let mut collector = DependencyCollector { cfg: &cfg, dependencies: Vec::new(), }; User::visit_dependencies(&mut collector); ``` -------------------------------- ### Resolve and export full dependency chain Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Retrieve transitive dependencies for a type and export all required definitions to the filesystem. ```rust use ts_rs::TS; use ts_rs::Config; // Assume these types exist: // - User (has field role: Role) // - Role (enum) // - Permission (referenced by Role) let cfg = Config::new(); // Get all dependencies transitively let all_deps = User::dependencies(&cfg); // Returns: // - Dependency { type_id: TypeId(Role), ts_name: "Role", output_path: "Role.ts" } // - Dependency { type_id: TypeId(Permission), ts_name: "Permission", output_path: "Permission.ts" } // Each dependency can be exported independently or as part of export_all User::export_all(&cfg)?; // Writes: User.ts, Role.ts, Permission.ts ``` -------------------------------- ### Find all types in a module Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md Collects type names into a vector using a custom visitor. ```rust use ts_rs::{TS, TypeVisitor, Config}; struct TypeNames { names: Vec, } impl TypeVisitor for TypeNames { fn visit(&mut self) { self.names.push(std::any::type_name::().to_string()); } } let mut visitor = TypeNames { names: Vec::new() }; User::visit_dependencies(&mut visitor); println!("Type names: {:?}", visitor.names); // Output: Type names: ["i32", "std::string::String", ...] ``` -------------------------------- ### Retrieve the output path for a type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Returns the relative path where the type would be exported, or None if the type is not exportable. ```rust User::output_path() // Some(PathBuf::from("User.ts")) String::output_path() // None (primitive) ``` -------------------------------- ### Enable smol_str-impl feature Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Use the smol_str-impl feature to map SmolStr types to TypeScript strings. ```toml [dependencies] ts-rs = { version = "12.0", features = ["smol_str-impl"] } smol_str = "0.3" ``` -------------------------------- ### Handle Serde Warnings Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Warnings are emitted for unsupported serde attributes when serde-compat is enabled. ```rust #[serde(unknown_attribute = "value")] struct User { } // warning: unsupported serde attribute: unknown_attribute ``` -------------------------------- ### Macro Crate Directory Structure Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Visual representation of the file organization within the macros/src directory. ```text macros/src/ ├── lib.rs # Main macro entry point ├── attr/ │ ├── mod.rs # Attribute parsing │ ├── struct.rs # Struct-specific attrs │ ├── enum.rs # Enum-specific attrs │ ├── field.rs # Field-specific attrs │ └── variant.rs # Variant-specific attrs ├── types/ │ ├── mod.rs # Type representation │ ├── named.rs # Named types (struct/enum) │ ├── tuple.rs # Tuple types │ ├── enum.rs # Enum generation │ └── ... ├── deps.rs # Dependency tracking └── utils.rs # Utility functions ``` -------------------------------- ### Programmatic export Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Exports a type and inspects the resulting dependencies programmatically. ```rust use ts_rs::{TS, Config, Dependency}; use std::path::PathBuf; fn export_with_dependencies(cfg: &Config) -> Result<(), Box> { // Export the main type User::export_all(cfg)?; // Inspect which types were exported let deps = User::dependencies(cfg); for dep in deps { let full_path = cfg.out_dir().join(&dep.output_path); println!("Exported {} to {}", dep.ts_name, full_path.display()); } Ok(()) } ``` -------------------------------- ### Implement IndexMap for TypeScript Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Enables support for indexmap::IndexMap and IndexSet, mapping them to TypeScript object types. ```rust use indexmap::IndexMap; #[derive(TS)] #[ts(export)] struct Index { mapping: IndexMap, } // Generated: type Index = { mapping: { [key in string]: number } }; ``` ```toml [dependencies] ts-rs = { version = "12.0", features = ["indexmap-impl"] } indexmap = "2" ``` -------------------------------- ### Configure Serde compatibility Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Shows how ts-rs attributes override Serde attributes when serde-compat is enabled. ```rust #[derive(Serialize, TS)] #[serde(rename_all = "snake_case")] #[ts(rename_all = "camelCase")] // ts-rs attr takes precedence struct User { first_name: String, } ``` -------------------------------- ### dependencies(cfg: &Config) -> Vec Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Recursively resolves all transitive type dependencies. ```APIDOC ## dependencies(cfg: &Config) -> Vec ### Description Recursively resolves all transitive type dependencies. Each returned Dependency contains the TypeScript name, type ID, and export path. ### Parameters - **cfg** (&Config) - Required - TypeScript generation configuration ### Returns - **Vec** - A vector of all transitive dependencies of the type. ``` -------------------------------- ### Track visit order Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-type-visitor.md Logs the order in which types are visited during traversal. ```rust use ts_rs::{TS, TypeVisitor, Config}; struct OrderedVisitor { visit_order: Vec, } impl TypeVisitor for OrderedVisitor { fn visit(&mut self) { let type_name = std::any::type_name::(); println!("Visiting #{}: {}", self.visit_order.len() + 1, type_name); self.visit_order.push(type_name.to_string()); } } let mut visitor = OrderedVisitor { visit_order: Vec::new(), }; User::visit_dependencies(&mut visitor); ``` -------------------------------- ### Manual Export in Tests Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Export bindings during test execution using a custom output directory configuration. ```rust #[cfg(test)] mod tests { use ts_rs::{TS, Config}; use super::*; #[test] fn export_bindings() { let cfg = Config::new() .with_out_dir("./generated/types"); User::export_all(&cfg) .expect("Failed to export User bindings"); } } ``` -------------------------------- ### Construct Dependency from Rust Type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Signature for the from_ty method used to create a Dependency instance from a type implementing TS. ```rust pub fn from_ty(cfg: &Config) -> Option ``` -------------------------------- ### Implement paginated results Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Use generic structs to define standard pagination structures for list endpoints. ```rust #[derive(Serialize, TS)] #[ts(export)] struct Page { items: Vec, total: i64, page: i32, per_page: i32, } #[derive(Serialize, TS)] #[ts(export)] struct User { id: i32, name: String, } // TypeScript: // type UserPage = Page; ``` -------------------------------- ### with_import_extension(ext: Option>) -> Self Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-config.md Sets the file extension used in generated import statements. ```APIDOC ## with_import_extension(ext: Option>) -> Self ### Description Sets the file extension used in generated import statements. Use None for no extension, "js" for JavaScript, or "ts" for TypeScript. ### Parameters - **ext** (Option>) - Required - File extension for imports, or None ### Returns Modified Config for method chaining. ``` -------------------------------- ### Configure ts-rs Programmatically Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Use the Config struct to define output directories, integer handling, and import extensions directly within your Rust code. ```rust use ts_rs::{Config, TS}; let cfg = Config::new() .with_out_dir("./generated/types") .with_large_int("bigint") .with_import_extension(Some("js")) .with_array_tuple_limit(100); User::export_all(&cfg)?; ``` -------------------------------- ### Run Export Generation Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Trigger TypeScript binding generation via cargo test commands. ```bash # Exports all #[ts(export)] types cargo test --lib # Runs a specific export test cargo test export_user_ts ``` -------------------------------- ### Test Macro Output Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/macro-system.md Unit tests to verify TypeScript declaration generation and string export functionality. ```rust #[test] fn test_user_generation() { use ts_rs::{TS, Config}; let cfg = Config::new(); let decl = User::decl(&cfg); assert!(decl.contains("id")); assert!(decl.contains("number")); } ``` ```rust #[test] fn test_user_export() { use ts_rs::{TS, Config}; let cfg = Config::new(); let ts_code = User::export_to_string(&cfg).unwrap(); assert!(ts_code.contains("export type User")); } ``` -------------------------------- ### Implement serde_json::Value Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Use the serde-json-impl feature to support mapping serde_json::Value types to TypeScript. ```rust #[derive(TS)] #[ts(export)] struct Config { #[cfg(feature = "serde-json-impl")] metadata: serde_json::Value, } ``` ```toml [dependencies] ts-rs = { version = "12.0", features = ["serde-json-impl"] } serde_json = "1" ``` -------------------------------- ### Enable format feature in Cargo.toml Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Enables the format feature to use dprint-plugin-typescript for automatic code formatting. ```toml [dependencies] ts-rs = { version = "12.0", features = ["format"] } ``` -------------------------------- ### Configure ts-rs features in Cargo.toml Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Common configurations for enabling specific integrations like JSON serialization, formatting, or the full suite of supported types. ```toml [dependencies] ts-rs = { version = "12.0", features = ["serde-json-impl", "uuid-impl", "chrono-impl"] } ``` ```toml [dependencies] ts-rs = { version = "12.0", features = ["format", "uuid-impl", "chrono-impl"] } ``` ```toml [dependencies] ts-rs = { version = "12.0", features = [ "format", "serde-json-impl", "uuid-impl", "url-impl", "chrono-impl", "bigdecimal-impl", "semver-impl", "ordered-float-impl", "smol_str-impl", "bson-uuid-impl", "bytes-impl", "indexmap-impl", "heapless-impl", "arrayvec-impl", "tokio-impl", "jiff-impl", "astrolabe-impl", ] } ``` -------------------------------- ### Handle default values Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Apply serde default to ensure fields are initialized with default values in the generated structure. ```rust #[derive(Serialize, TS)] #[serde(default)] #[ts(export)] struct Config { timeout: u64, retries: u32, verbose: bool, } ``` -------------------------------- ### Export a type and its dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Recursively exports the type and all of its transitive dependencies to their designated files. ```rust let cfg = Config::from_env(); User::export_all(&cfg)?; // Writes User.ts, Role.ts, and all other dependencies ``` -------------------------------- ### Export a single type to the filesystem Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Exports only the specific type to the filesystem without its dependencies. The output path is determined by the configuration or the type name. ```rust let cfg = Config::new().with_out_dir("./bindings"); User::export(&cfg)?; // Writes to ./bindings/User.ts ``` -------------------------------- ### Build import statements Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Groups dependencies by their output path to generate TypeScript import statements. ```rust use ts_rs::{TS, Config, Dependency}; use std::collections::BTreeMap; let cfg = Config::new(); let deps = User::dependencies(&cfg); // Group dependencies by output path let mut imports: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); for dep in &deps { let path = dep.output_path.to_str().unwrap(); imports.entry(path) .or_insert_with(Vec::new) .push(&dep.ts_name); } // Generate import statements for (path, types) in imports { let types_str = types.join(", "); println!("import type {{ {} }} from \"{}\";", types_str, path); } ``` -------------------------------- ### output_path() Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Returns the relative path where the type should be exported. ```APIDOC ## output_path() ### Description Returns the output path determined by #[ts(export_to = "...")] or the default .ts. Primitive types return None. ### Returns - **Option** - Relative path where this type should be exported, or None if not exportable. ``` -------------------------------- ### Implement heapless for TypeScript Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Enables support for heapless::Vec and heapless::String, mapping them to standard TypeScript Array and string types. ```rust use heapless::Vec; #[derive(TS)] #[ts(export)] struct LimitedList { items: Vec, } // Generated: type LimitedList = { items: Array }; ``` ```toml [dependencies] ts-rs = { version = "12.0", features = ["heapless-impl"] } heapless = "0.9" ``` -------------------------------- ### Apply Case Conversion Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/usage-examples.md Use rename_all to automatically convert field names to specific casing conventions like camelCase. ```rust #[derive(Serialize, TS)] #[ts(rename_all = "camelCase")] #[ts(export)] struct UserProfile { user_id: i32, first_name: String, last_name: String, } ``` ```typescript export type UserProfile = { userId: number, firstName: string, lastName: string, }; ``` -------------------------------- ### Define and Use name() Method Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-ts-trait.md Returns the full TypeScript name of the type, including generic parameters. ```rust fn name(cfg: &Config) -> String ``` ```rust // For Vec Vec::::name(cfg) // "Array" // For Option Option::::name(cfg) // "number | null" // For a struct User::name(cfg) // "User" ``` -------------------------------- ### Deduplicate dependencies using BTreeSet Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference-dependency.md Use a BTreeSet to automatically deduplicate dependency records based on their defined ordering. ```rust use ts_rs::{TS, Config}; use std::collections::BTreeSet; let cfg = Config::new(); let deps = User::dependencies(&cfg); // BTreeSet automatically deduplicates by identity let unique_deps: BTreeSet<_> = deps.into_iter().collect(); ```