### 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 ``` -------------------------------- ### Example complete configuration in .cargo/config.toml Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Provides a complete example of ts-rs configuration settings within the .cargo/config.toml file, including relative path for export directory. ```toml # .cargo/config.toml [env] # Relative path from CARGO_MANIFEST_DIR TS_RS_EXPORT_DIR = { value = "src/bindings", relative = true } # Or absolute path # TS_RS_EXPORT_DIR = "/home/user/project/bindings" ``` -------------------------------- ### Example: Using output_path for User and i32 Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Demonstrates how to use the `output_path` function to get the export path for a custom type (`User`) and a primitive type (`i32`). Shows that `User` returns `Some(PathBuf::from("User.ts"))` while `i32` returns `None`. ```rust use ts_rs::TS; use std::path::PathBuf; let path = User::output_path(); // Some(PathBuf::from("User.ts")) let num_path = i32::output_path(); // None - primitives cannot be exported ``` -------------------------------- ### Create New Config with Defaults Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Initializes a new Config instance with default settings. Useful for starting configuration. ```rust use ts_rs::Config; let config = Config::new(); let export_dir = config.out_dir(); assert_eq!(export_dir.to_str(), Some("./bindings")); ``` -------------------------------- ### Full ts-rs Derive Macro Example Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/derive-macro.md A comprehensive example showcasing `ts-rs` derive macro with `serde` integration. It includes `export`, `rename`, `rename_all`, `optional` fields, and `inline` types, generating a TypeScript type definition. ```rust use serde::Serialize; use ts_rs::TS; #[derive(Serialize, TS)] #[ts(export, rename = "IUser", rename_all = "camelCase")] struct User { user_id: i32, first_name: String, #[ts(optional)] nickname: Option, #[ts(inline)] role: UserRole, } #[derive(Serialize, TS)] #[serde(rename_all = "UPPERCASE")] enum UserRole { Admin, User, } // Generates in ./bindings/IUser.ts: // export type IUser = { userId: number, firstName: string, nickname?: string, role: "ADMIN" | "USER" } ``` -------------------------------- ### Inline TypeVisitor Implementation Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md Demonstrates how to implement TypeVisitor inline for simple use cases. This example collects type names into a vector. ```rust use ts_rs::{TS, TypeVisitor, Config}; #[derive(TS)] struct Person { name: String, } let mut names = Vec::new(); let cfg = Config::new(); struct Visitor<'a>(&'a mut Vec, &'a Config); impl TypeVisitor for Visitor<'_> { fn visit(&mut self) { self.0.push(T::name(self.1)); } } Person::visit_dependencies(&mut Visitor(&mut names, &cfg)); ``` -------------------------------- ### Basic ts-rs Import and Usage Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/derive-macro.md Demonstrates the minimal setup required to use the `ts-rs` derive macro by importing the `TS` trait and deriving it for a struct. ```rust use ts_rs::TS; // Re-exported from ts_rs_macros::TS #[derive(TS)] struct MyType; ``` -------------------------------- ### TypeScript Formatting Example Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Compares the generated TypeScript output for a `User` type with and without the `format` feature enabled, showing the effect of dprint formatting. ```typescript // Without format export type User={id:number;name:string;role:Role;}; // With format export type User = { id: number; name: string; role: Role; }; ``` -------------------------------- ### Add ts-rs Dependency to Cargo.toml Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/INDEX.md Shows the basic dependency addition required in Cargo.toml to start using the ts-rs crate. ```toml [dependencies] ts-rs = "12.0" ``` -------------------------------- ### TypeScript output for TS_RS_IMPORT_EXTENSION=ts Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of generated TypeScript import statements using the '.ts' extension. ```typescript // With TS_RS_IMPORT_EXTENSION=ts import { User } from "./User.ts"; import { Role } from "./Role.ts"; ``` -------------------------------- ### Programmatic Export with Error Handling in Rust Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Shows how to programmatically export types using `export_all` and handle potential `ExportError`s. This example includes specific handling for IO and unexportable type errors, exiting with a non-zero status code on failure. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct Product { id: i32, name: String, price: f64, } fn main() { let cfg = Config::new() .with_out_dir("./src/bindings"); if let Err(e) = Product::export_all(&cfg) { match e { ts_rs::ExportError::Io(io_err) => { eprintln!("IO error during export: {}", io_err); std::process::exit(1); } ts_rs::ExportError::CannotBeExported(name) => { eprintln!("Type cannot be exported: {}", name); std::process::exit(1); } _ => { eprintln!("Export failed: {}", e); std::process::exit(1); } } } } ``` -------------------------------- ### Get Output Directory Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Retrieves the configured output directory path for generated bindings. Useful for verifying the export location. ```rust let config = Config::new(); let dir = config.out_dir(); println!("Export to: {}", dir.display()); ``` -------------------------------- ### TypeScript output for TS_RS_IMPORT_EXTENSION=js Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of generated TypeScript import statements using the '.js' extension. ```typescript // With TS_RS_IMPORT_EXTENSION=js import { User } from "./User.js"; import { Role } from "./Role.js"; ``` -------------------------------- ### Internal Implementation: Dependency Collection Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md An example of how ts-rs internally uses TypeVisitor to collect dependencies during type processing. ```rust struct DependencyVisit<'a> { cfg: &'a Config, deps: &'a mut Vec, } impl TypeVisitor for DependencyVisit<'_> { fn visit(&mut self) { if let Some(dep) = Dependency::from_ty::(self.cfg) { self.deps.push(dep); } } } ``` -------------------------------- ### TypeScript output with no import extension (default) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of generated TypeScript import statements using the default behavior (no file extension). ```typescript // With no extension (default) import { User } from "./User"; import { Role } from "./Role"; ``` -------------------------------- ### Programmatic Configuration for ts-rs Export Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/quick-reference.md Configures ts-rs export settings programmatically using `Config::new()`. This example sets the output directory, large integer type, and import extension. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct User { id: i64, name: String, } fn main() -> Result<(), ts_rs::ExportError> { let cfg = Config::new() .with_out_dir("./generated/types") .with_large_int("bigint") .with_import_extension(Some("js")); User::export_all(&cfg)?; Ok(()) } ``` -------------------------------- ### Generating TypeScript Strings in Rust Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Illustrates how to generate TypeScript bindings as a string using `export_to_string` without writing to disk. This example includes error handling for the generation process. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct ApiResponse { status: i32, data: String, } fn generate_types() -> Result { let cfg = Config::new(); // Generate without writing to disk ApiResponse::export_to_string(&cfg).map_err(|e| { eprintln!("Failed to generate bindings: {}", e); e }) } ``` -------------------------------- ### Get Import Extension Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Retrieves the file extension used for import statements, if it has been set. ```rust pub fn import_extension(&self) -> Option<&str> ``` -------------------------------- ### Ts-rs API Reference Overview Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/COMPLETION_SUMMARY.txt This section outlines the structure and entry points for the ts-rs API documentation, guiding users to the most relevant information based on their needs. ```APIDOC ## Ts-rs API Documentation Structure ### Overview This documentation provides a complete reference for the ts-rs library, generated directly from its source code. It covers all exported functions, types, environment variables, feature flags, macro attributes, and error variants. ### Entry Points Users can access the documentation through several entry points tailored to different needs: 1. **README.md**: Provides an overall orientation and guidance based on user roles. 2. **INDEX.md**: Serves as a master reference with lookup tables for comprehensive information. 3. **quick-reference.md**: Offers essential patterns and solutions for common use cases. ### Reference Paths Detailed information is organized into specific sections: - **Configuration**: Documented in `configuration.md` and `feature-flags.md`. - **Types & Support**: Covered in `types.md` and `feature-flags.md`. - **Attributes**: Documentation for derive macros is in `derive-macro.md` and `quick-reference.md`. - **API Details**: Specific API references are located in the `api-reference/` directory, including `ts-trait.md`, `config.md`, `dependency.md`, `type-visitor.md`, and `is-option.md`. - **Troubleshooting**: Guidance for error handling is provided in `errors.md` and `quick-reference.md`. ### Compliance and Content - All exported symbols are documented with exact import paths. - Parameter tables include name, type, default value, and description. - Code examples demonstrate usage patterns, not tests. - Cross-references link related documentation pages. - Source file locations are cited for detailed reference (e.g., `ts-rs/src/lib.rs:369-545`). - Content is purely technical, avoiding marketing copy or tutorials. - Markdown format with tables and code blocks is used for clarity and structure. ``` -------------------------------- ### Conditional Compilation with Features Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Examples of conditional compilation using Rust's cfg attribute for feature flags like uuid-impl and chrono-impl. ```rust #[cfg(feature = "uuid-impl")] fn uses_uuid() { use uuid::Uuid; // UUID support available } ``` ```rust #[cfg(feature = "chrono-impl")] fn uses_chrono() { use chrono::{DateTime, Utc}; // DateTime support available } ``` -------------------------------- ### Rust Struct with Serde Attributes Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Example demonstrating the use of `#[serde(rename_all = "camelCase")]` with the `serde-compat` feature enabled. This adjusts the generated TypeScript output. ```rust use serde::Serialize; use ts_rs::TS; #[derive(Serialize, TS)] #[serde(rename_all = "camelCase")] struct User { first_name: String, // becomes firstName in TS } ``` -------------------------------- ### Handling Export Errors in Rust Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md Demonstrates how to handle `ExportError` variants when exporting multiple types using `export_all`. This example shows specific error handling for `Io` and `CannotBeExported` errors, with a fallback for other error types. ```rust use ts_rs::{TS, Config, ExportError}; #[derive(TS)] #[ts(export)] struct User { id: i32, name: String, } fn export_types() -> Result<(), ExportError> { let cfg = Config::from_env(); match User::export_all(&cfg) { Ok(()) => { println!("Export succeeded"); Ok(()) } Err(ExportError::Io(e)) => { eprintln!("Failed to write files: {}", e); Err(ExportError::Io(e)) } Err(ExportError::CannotBeExported(type_name)) => { eprintln!("Cannot export type: {}", type_name); Err(ExportError::CannotBeExported(type_name)) } Err(e) => { eprintln!("Export error: {}", e); Err(e) } } } ``` -------------------------------- ### Get Type Identifier Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Returns the identifier of a type, excluding generic parameters. For example, 'User' for both `User` and `User`. ```rust fn ident(cfg: &Config) -> String ``` -------------------------------- ### Build the project Source: https://github.com/aleph-alpha/ts-rs/blob/main/CONTRIBUTING.md Build the project using Cargo. ```shell cargo build ``` -------------------------------- ### Example of Serde Warning Suppression Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md This example shows a typical warning message generated by ts-rs for an unsupported serde attribute (`serialize_with`) when the `no-serde-warnings` flag is not enabled. ```rust warning: unsupported serde attribute: `serialize_with` --> src/lib.rs:42:15 | 42 | #[serde(serialize_with = "custom")] | ^^^^^^^^^ ``` -------------------------------- ### 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 ``` -------------------------------- ### Implement TypeVisitor and Visit Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Shows how to implement the `TypeVisitor` trait and use `visit_dependencies` to handle each dependency of a type. This is useful for custom dependency management or analysis. ```rust struct Dependencies; impl TypeVisitor for Dependencies { fn visit(&mut self) { // Handle each dependency } } let mut visitor = Dependencies; User::visit_dependencies(&mut visitor); ``` -------------------------------- ### TypeScript output for TS_RS_LARGE_INT=bigint Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of how a large integer is represented in TypeScript when TS_RS_LARGE_INT is set to 'bigint'. ```typescript // With TS_RS_LARGE_INT=bigint let id: bigint = 123456789012345n; ``` -------------------------------- ### Getting Recursive Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/dependency.md Retrieves all direct and transitive dependencies for a given type using the TS trait. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct User { id: i32, role: Role, } #[derive(TS)] struct Role { name: String, } let cfg = Config::new(); let deps = User::dependencies(&cfg); // Contains User, Role, and their transitive dependencies ``` -------------------------------- ### Configure ts-rs via .cargo/config.toml Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/INDEX.md Demonstrates how to configure ts-rs export settings using the .cargo/config.toml file for project-wide settings. ```toml # .cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "src/types", relative = true } TS_RS_LARGE_INT = "bigint" ``` -------------------------------- ### Cloning and Comparing Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/dependency.md Demonstrates cloning a Dependency instance and asserting equality between the original and the clone. ```rust use ts_rs::Dependency; let dep1 = Dependency { type_id: std::any::TypeId::of::(), ts_name: "number".to_string(), output_path: "primitive.ts".into(), }; let dep2 = dep1.clone(); assert_eq!(dep1, dep2); ``` -------------------------------- ### Get Array Tuple Limit Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Retrieves the current maximum array size configured for TypeScript tuple representation. ```rust pub fn array_tuple_limit(&self) -> usize ``` -------------------------------- ### Programmatic Configuration with Config Builder Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Use the `Config` builder pattern for runtime configuration. This allows setting output directory, large integer handling, import extension, and array tuple limits. ```rust use ts_rs::Config; let config = Config::new() .with_out_dir("./src/generated/types") .with_large_int("bigint") .with_import_extension(Some("js")) .with_array_tuple_limit(32); // Use for export MyType::export_all(&config)?; ``` -------------------------------- ### Integration: dependencies Method Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md Shows the implementation of the `dependencies` method using TypeVisitor to gather all type dependencies. ```rust fn dependencies(cfg: &Config) -> Vec where Self: 'static, { struct Visit<'a>(&'a Config, &'a mut Vec); impl TypeVisitor for Visit<'_> { fn visit(&mut self) { let Visit(cfg, deps) = self; if let Some(dep) = Dependency::from_ty::(cfg) { deps.push(dep); } } } let mut deps: Vec = vec![]; Self::visit_dependencies(&mut Visit(cfg, &mut deps)); deps } ``` -------------------------------- ### TypeScript output for TS_RS_LARGE_INT=string Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of how a large integer is represented in TypeScript when TS_RS_LARGE_INT is set to 'string', preserving full precision. ```typescript // With TS_RS_LARGE_INT=string let id: string = "123456789012345"; ``` -------------------------------- ### Configuration Precedence with Environment Variables Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Demonstrates how `Config::from_env()` reads configuration. Environment variables take precedence over defaults, and programmatic overrides always win. ```rust use ts_rs::Config; // If TS_RS_EXPORT_DIR is set to "./custom", uses that // If TS_RS_EXPORT_DIR is not set, uses "./bindings" let cfg = Config::from_env(); // Programmatic override always wins let cfg = Config::from_env() .with_out_dir("./forced/path"); // Forces this path regardless of env var ``` -------------------------------- ### Derive TS Trait for Rust Struct Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/INDEX.md Basic example of deriving the TS trait for a Rust struct and enabling export. ```rust use ts_rs::TS; #[derive(TS)] #[ts(export)] struct User { id: i32, name: String, } ``` -------------------------------- ### Create Config from Environment Variables Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Initializes a Config by reading settings from environment variables. Supports TS_RS_EXPORT_DIR, TS_RS_IMPORT_EXTENSION, TS_RS_LARGE_INT, and TS_RS_USE_V11_HASHMAP. ```rust use ts_rs::Config; std::env::set_var("TS_RS_EXPORT_DIR", "./types"); std::env::set_var("TS_RS_LARGE_INT", "number"); let config = Config::from_env(); assert_eq!(config.large_int(), "number"); ``` -------------------------------- ### Get Large Integer Type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Retrieves the currently configured TypeScript type for large integers. Useful for inspecting the configuration. ```rust let config = Config::new(); let large_int_type = config.large_int(); // "bigint" ``` -------------------------------- ### 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 ``` -------------------------------- ### Config::new Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Creates a new Config instance with default values. The defaults are: `large_int_type` = "bigint", `export_dir` = "./bindings", `import_extension` = None, and `array_tuple_limit` = 64. ```APIDOC ## Config::new ### Description Creates a new `Config` with default values. ### Returns `Config` instance with: - `large_int_type` = `"bigint"` - `export_dir` = `./bindings` - `import_extension` = `None` - `array_tuple_limit` = `64` ### Example ```rust use ts_rs::Config; let config = Config::new(); let export_dir = config.out_dir(); assert_eq!(export_dir.to_str(), Some("./bindings")); ``` ``` -------------------------------- ### Programmatic Export with Custom Config Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Demonstrates creating a custom `Config` object programmatically to specify output directory, large integer type, import extension, and array tuple limit before exporting types. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct User { id: i32, name: String, } // Create custom configuration let config = Config::new() .with_out_dir("./bindings") .with_large_int("bigint") .with_import_extension(Some("js")) .with_array_tuple_limit(32); // Export with configuration User::export_all(&config)?; ``` -------------------------------- ### TypeScript output for TS_RS_LARGE_INT=number Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Example of how a large integer is represented in TypeScript when TS_RS_LARGE_INT is set to 'number', highlighting potential precision loss. ```typescript // With TS_RS_LARGE_INT=number let id: number = 123456789012345; // May lose precision ``` -------------------------------- ### Web Project Configuration (.cargo/config.toml) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Configuration for a web project using ESM imports. Sets the output directory, large integer type, and import extension via environment variables in `.cargo/config.toml`. ```toml # .cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "src/types", relative = true } TS_RS_LARGE_INT = "bigint" TS_RS_IMPORT_EXTENSION = "js" ``` -------------------------------- ### 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. ``` -------------------------------- ### Rust Struct with serde_json::Value Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Example demonstrating how to derive `TS` for a struct containing a `serde_json::Value` field. With the `serde_json-impl` feature, this will be exported as `any` in TypeScript. ```rust use ts_rs::TS; use serde_json::Value; #[derive(TS)] #[ts(export)] struct Data { metadata: Value, // Becomes any } ``` -------------------------------- ### Programmatically Export Type and Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Demonstrates how to use `export_all()` to export a Rust type along with all its dependencies. This is useful for generating TypeScript definitions for complex types and their related types. The output directory can be configured using `Config::new().with_out_dir()`. ```rust use ts_rs::{TS, Config}; let mut cfg = Config::new().with_out_dir("./generated/types"); User::export_all(&cfg)?; // Exports User and all types it references (Role, etc.) ``` -------------------------------- ### Legacy JavaScript Support Configuration (.cargo/config.toml) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Configuration for legacy JavaScript support. Sets the output directory, uses 'string' for large integers due to JavaScript limitations, and omits the import extension for CommonJS compatibility. ```toml # .cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "lib/ts", relative = true } TS_RS_LARGE_INT = "string" # JavaScript can't safely handle large numbers TS_RS_IMPORT_EXTENSION = "" # No extension for CommonJS compatibility ``` -------------------------------- ### Displaying ExportError Variants Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md All `ExportError` variants implement `Display` and `Debug`. This example shows how to print the display representation of `CannotBeExported` and the debug representation of `InvalidImportExtension`. ```rust use ts_rs::ExportError; let err = ExportError::CannotBeExported("i32"); println!("{}", err); // "this type cannot be exported" let err = ExportError::InvalidImportExtension; println!("{:?}", err); // ExportError::InvalidImportExtension ``` -------------------------------- ### Config::out_dir Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Returns the output directory path where bindings will be exported. ```APIDOC ## Config::out_dir ### Description Returns the output directory where bindings will be exported. ### Returns Directory path as `&Path`. ### Example ```rust let config = Config::new(); let dir = config.out_dir(); println!("Export to: {}", dir.display()); ``` ``` -------------------------------- ### Get TypeScript Type Name Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Retrieves the TypeScript representation of a Rust type, including generic parameters. Useful for understanding how a type will be represented in TypeScript. ```rust use ts_rs::{TS, Config}; let cfg = Config::new(); let name = String::name(&cfg); // "string" let vec_name = Vec::::name(&cfg); // "Array" ``` -------------------------------- ### Testing Configuration with Config Builder Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Configuration for testing purposes. Uses the `Config` builder to set a specific output directory, use 'number' for large integers, and a smaller array tuple limit. ```rust use ts_rs::Config; let config = Config::new() .with_out_dir("./test_output") .with_large_int("number") .with_array_tuple_limit(4); // Smaller for testing Type::export_all(&config)?; ``` -------------------------------- ### Wrapper Type Implementation for Primitive TS Type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/advanced-usage.md Implement `TS` for a wrapper type to map it to a primitive TypeScript type. For example, map a `Milliseconds` struct to `number`. ```rust use ts_rs::TS; pub struct Milliseconds(pub u64); impl TS for Milliseconds { type WithoutGenerics = Self; type OptionInnerType = Self; fn name(_: &ts_rs::Config) -> String { "number".to_string() // Treat as number in TS } fn inline(cfg: &ts_rs::Config) -> String { Self::name(cfg) } } ``` -------------------------------- ### Derive TS for Struct with Tuple Fields Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/types.md Example of deriving TS for a struct containing tuple fields. This demonstrates how Rust tuples are translated into TypeScript tuple types. ```rust use ts_rs::TS; #[derive(TS)] struct Pair { coordinates: (f64, f64), named: (String, i32), } // Generates: // export type Pair = { // coordinates: [number, number], // named: [string, number] // } ``` -------------------------------- ### 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 ``` -------------------------------- ### export_all Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Manually exports the current type and all of its dependencies to the filesystem. This method is recommended for programmatic export when not using the `#[ts(export)]` attribute. ```APIDOC ## export_all ### Description Manually exports this type and all of its dependencies to the filesystem. Recommended for programmatic export without using the `#[ts(export)]` attribute. ### Signature ```rust fn export_all(cfg: &Config) where Self: 'static, ``` ### Parameters #### Path Parameters - **cfg** (`&Config`) - Required - Configuration with export directory settings. ### Returns `Ok(())` on success, or `ExportError` if any type cannot be exported. ### Errors - `ExportError::CannotBeExported` - A type in the dependency tree has no output path. - `ExportError::Io` - Filesystem write failed. ### Example ```rust use ts_rs::{TS, Config}; let mut cfg = Config::new().with_out_dir("./generated/types"); User::export_all(&cfg)?; // Exports User and all types it references (Role, etc.) ``` ``` -------------------------------- ### Rust Struct with uuid::Uuid Type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Example demonstrating how to derive `TS` for a struct containing a `uuid::Uuid` field. With the `uuid-impl` feature, this will be exported as a string in TypeScript. ```rust use ts_rs::TS; use uuid::Uuid; #[derive(TS)] #[ts(export)] struct User { id: Uuid, // Becomes string in TypeScript } ``` -------------------------------- ### Production Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Minimal dependencies for production builds. Use this configuration to avoid including heavy formatting dependencies. ```toml [dependencies] ts-rs = { version = "12.0", default-features = false, features = ["serde-compat"] } ``` -------------------------------- ### Basic Usage of #[derive(TS)] Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/derive-macro.md Demonstrates the fundamental usage of the #[derive(TS)] macro for structs and enums. Ensure you have `use ts_rs::TS;` imported. ```rust use ts_rs::TS; #[derive(TS)] #[ts(export)] struct User { id: i32, name: String, } #[derive(TS)] #[ts(export)] enum Status { Active, Inactive, } ``` -------------------------------- ### Rust Struct with chrono::DateTime Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Example demonstrating how to derive `TS` for a struct containing a `chrono::DateTime` field. With the `chrono-impl` feature, this will be exported as a string in TypeScript. ```rust use ts_rs::TS; use chrono::{DateTime, Utc}; #[derive(TS)] #[ts(export)] struct Event { created_at: DateTime, // Becomes string } ``` -------------------------------- ### Organize Multiple TypeScript Export Targets Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/advanced-usage.md Demonstrates how to use `#[ts(export_to = "...")]` to place generated TypeScript types into a structured directory, managing dependencies between files. ```rust // api/user.rs #[derive(TS)] #[ts(export, export_to = "api/users/User.ts")] pub struct User { /* ... */ } // api/product.rs #[derive(TS)] #[ts(export, export_to = "api/products/Product.ts")] pub struct Product { /* ... */ } // auth/role.rs #[derive(TS)] #[ts(export, export_to = "auth/Role.ts")] pub struct Role { /* ... */ } // Generates tree: // bindings/ // ├── api/ // │ ├── users/User.ts // │ └── products/Product.ts // └── auth/Role.ts ``` -------------------------------- ### Configure ts-rs Export Settings Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/INDEX.md Shows different ways to configure the ts-rs export process, including reading settings from environment variables, programmatic configuration, and using .cargo/config.toml. ```rust // From environment let cfg = Config::from_env(); // Programmatic let cfg = Config::new() .with_out_dir("./bindings") .with_large_int("bigint") .with_import_extension(Some("js")); // Via .cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "bindings", relative = true } TS_RS_LARGE_INT = "bigint" ``` -------------------------------- ### Usage: Collecting Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md Demonstrates implementing TypeVisitor to count type dependencies. This is useful for analyzing the structure of types. ```rust use ts_rs::{TS, TypeVisitor, Config}; struct DependencyCollector { count: usize, } impl TypeVisitor for DependencyCollector { fn visit(&mut self) { self.count += 1; println!("Visited type"); } } #[derive(TS)] struct User { id: i32, role: Role, } #[derive(TS)] struct Role { name: String, } let mut collector = DependencyCollector { count: 0 }; User::visit_dependencies(&mut collector); println!("Found {} dependencies", collector.count); ``` -------------------------------- ### Enable serde-compat Feature Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md This TOML snippet shows how to enable the default `serde-compat` feature for ts-rs, which allows parsing of serde attributes. ```toml [dependencies] ts-rs = "12.0" # Includes serde-compat by default ``` -------------------------------- ### Get Output Path for Exportable Types Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Retrieves the relative output path for exporting a Rust type to TypeScript. Primitive types return `None` as they cannot be exported. The export path can be customized using `#[ts(export_to = "..")]`. ```rust fn output_path() -> Option ``` -------------------------------- ### Web Project with Common ts-rs Types Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md This configuration is suitable for web projects, enabling common features like serde compatibility, chrono, uuid, and formatting. It includes necessary dependencies for these features. ```toml [dependencies] ts-rs = { version = "12.0", features = [ "serde-compat", "chrono-impl", "uuid-impl", "format", ] } chrono = { version = "0.4", features = ["serde"] } uuid = { version = "1.0", features = ["v4", "serde"] } ``` -------------------------------- ### Development Features for ts-rs Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md This configuration enables 'serde-compat' and 'format' features, ideal for development. It ensures serde compatibility and pretty-prints the output for easier inspection. ```toml [dependencies] ts-rs = { version = "12.0", features = ["serde-compat", "format"] } ``` -------------------------------- ### Config::from_env Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Creates a new Config instance by reading values from environment variables. It supports `TS_RS_EXPORT_DIR`, `TS_RS_IMPORT_EXTENSION`, `TS_RS_LARGE_INT`, and `TS_RS_USE_V11_HASHMAP`. ```APIDOC ## Config::from_env ### Description Creates a new `Config` reading values from environment variables. Supports the following variables: | Variable | Description | Default | |----------|-------------|---------| | `TS_RS_EXPORT_DIR` | Base directory for exported bindings | `./bindings` | | `TS_RS_IMPORT_EXTENSION` | File extension for import statements | None | | `TS_RS_LARGE_INT` | TypeScript type for large integers | `bigint` | | `TS_RS_USE_V11_HASHMAP` | (Deprecated) Use v11 HashMap behavior | `false` | ### Returns `Config` with values from environment or defaults. ### Example ```rust use ts_rs::Config; std::env::set_var("TS_RS_EXPORT_DIR", "./types"); std::env::set_var("TS_RS_LARGE_INT", "number"); let config = Config::from_env(); assert_eq!(config.large_int(), "number"); ``` ``` -------------------------------- ### visit_dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Iterates over all dependencies of the current type. This method is called internally to recursively resolve and export all types used by the current type. ```APIDOC ## visit_dependencies ### Description Iterates over all dependencies of this type. Called internally to recursively resolve and export all types used by this type. ### Signature ```rust fn visit_dependencies(_: &mut impl TypeVisitor) where Self: 'static, ``` ### Parameters #### Path Parameters - **v** (`&mut impl TypeVisitor`) - Required - Visitor to visit each dependency. ### Example ```rust struct Dependencies; impl TypeVisitor for Dependencies { fn visit(&mut self) { // Handle each dependency } } let mut visitor = Dependencies; User::visit_dependencies(&mut visitor); ``` ``` -------------------------------- ### Rust Function Signature: export_all Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md This is a function signature for `export_all`. It takes a configuration reference and manually exports the type and all of its dependencies to the filesystem. This is recommended for programmatic export. ```rust fn export_all(cfg: &Config) -> Result<(), ExportError> where Self: 'static, ``` -------------------------------- ### Node.js Project Configuration (.cargo/config.toml) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Configuration for a Node.js project using CommonJS. Specifies output directory, large integer type for JSON serialization, and import extension. ```toml # .cargo/config.toml [env] TS_RS_EXPORT_DIR = { value = "dist/types", relative = true } TS_RS_LARGE_INT = "string" # For full precision in JSON serialization TS_RS_IMPORT_EXTENSION = "js" ``` -------------------------------- ### Usage: Collecting Generic Type Names Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md Shows how to implement TypeVisitor to collect the names of generic type parameters. This is helpful for understanding generic type usage. ```rust use ts_rs::{TS, TypeVisitor}; struct GenericCollector { names: Vec, } impl TypeVisitor for GenericCollector { fn visit(&mut self) { let cfg = ts_rs::Config::new(); self.names.push(T::name(&cfg)); } } #[derive(TS)] struct Container { first: T, second: U, } let mut collector = GenericCollector { names: Vec::new() }; Container::::visit_generics(&mut collector); ``` -------------------------------- ### Namespace Types by Version Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/advanced-usage.md Create distinct types for different API versions, such as `UserV1` and `UserV2`. Export each version to its own namespaced path. ```rust #[derive(TS)] #[ts(export, export_to = "api/v1/User.ts")] pub struct UserV1 { pub id: i32, } #[derive(TS)] #[ts(export, export_to = "api/v2/User.ts")] pub struct UserV2 { pub id: i32, pub email: String, } ``` -------------------------------- ### Exporting a Single Type to Disk in Rust Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/errors.md This snippet shows how to export a single type to disk using `Item::export(&cfg)`. It highlights potential errors such as the export directory not existing or permission issues. ```rust use ts_rs::{TS, Config}; #[derive(TS)] #[ts(export)] struct Item { id: i32, } let cfg = Config::from_env(); Item::export(&cfg)?; // Can fail if export_dir doesn't exist or permissions issue ``` -------------------------------- ### 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. ``` -------------------------------- ### Full-Featured ts-rs Configuration Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md This configuration enables all available features for ts-rs, providing comprehensive support for various crates and functionalities. It's useful for projects requiring maximum integration. ```toml [dependencies] ts-rs = { version = "12.0", features = [ "serde-compat", "chrono-impl", "uuid-impl", "url-impl", "serde-json-impl", "bigdecimal-impl", "bytes-impl", "indexmap-impl", "ordered-float-impl", "heapless-impl", "arrayvec-impl", "semver-impl", "smol_str-impl", "tokio-impl", "format", ] } ``` -------------------------------- ### Manually Export a Single Rust Type Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Shows how to manually export a single Rust type to the filesystem using the `export()` function. This requires a `Config` object, typically created with `Config::from_env()`. Errors can occur if the type cannot be exported or if I/O fails. ```rust use ts_rs::{TS, Config}; let cfg = Config::from_env(); User::export(&cfg)?; ``` -------------------------------- ### Enable no-serde-warnings Feature Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md This TOML snippet demonstrates how to enable both `serde-compat` and `no-serde-warnings` features for ts-rs. The `no-serde-warnings` flag suppresses warnings for unsupported serde attributes. ```toml [dependencies] ts-rs = { version = "12.0", features = ["serde-compat", "no-serde-warnings"] } ``` -------------------------------- ### Resolve and Print Type Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Demonstrates how to resolve all dependencies of a Rust type using `dependencies()` and iterate through the resulting `Dependency` structs to print their TypeScript names and output paths. Requires `ts_rs` and `Config` imports. ```rust use ts_rs::{TS, Config}; let cfg = Config::new(); let deps = User::dependencies(&cfg); for dep in deps { println!("Type: {}, Path: {}", dep.ts_name, dep.output_path.display()); } ``` -------------------------------- ### Testing Dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md Dependencies for testing environments. Use in dev-dependencies to avoid pulling in heavy formatting dependencies in production. ```toml [dev-dependencies] ts-rs = { version = "12.0", features = ["serde-compat", "format"] } ``` -------------------------------- ### Config Construction and Builder Methods Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/INDEX.md The `Config` struct allows customization of the TypeScript generation process. It can be constructed with default settings or read from environment variables, and its behavior can be further refined using builder methods. ```APIDOC ## `Config` Struct Configuration for TypeScript generation and export behavior. ### Construction - `Config::new()` - Creates a new `Config` with default settings. - `Config::from_env()` - Creates a `Config` by reading settings from environment variables. ### Builder Methods - `with_out_dir(dir)` - Sets the base directory for exported bindings. - `with_large_int(type)` - Specifies the TypeScript type for large integers (e.g., `bigint`). - `with_import_extension(ext)` - Sets the file extension for generated import paths. - `with_array_tuple_limit(n)` - Defines the size limit for treating arrays as tuples. ``` -------------------------------- ### Check Export Directory Configuration Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/quick-reference.md Verify the configured export directory by reading it from the environment. Ensure TS_RS_EXPORT_DIR is set correctly in your .cargo/config.toml. ```rust let cfg = Config::from_env(); println!("Export dir: {}", cfg.out_dir().display()); ``` -------------------------------- ### Add heapless Crate Implementation Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/feature-flags.md To use ts-rs with the heapless crate, add the 'heapless-impl' feature and the heapless dependency to your Cargo.toml. ```toml [dependencies] ts-rs = { version = "12.0", features = ["heapless-impl"] } heapless = "0.8" ``` -------------------------------- ### Reading ts-rs Configuration from Environment Variables Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/quick-reference.md Loads ts-rs configuration settings directly from environment variables using `Config::from_env()`. This allows for flexible configuration without modifying code. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct Type; fn main() -> Result<(), ts_rs::ExportError> { let cfg = Config::from_env(); Type::export_all(&cfg)?; Ok(()) } ``` -------------------------------- ### HashMap TypeScript output difference (v12 vs v11) Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/configuration.md Illustrates the difference in TypeScript output for HashMap between the current v12 default and the deprecated v11 behavior. ```typescript // v12 (current default) - enum keys use optional, non-enum keys required HashMap // { [key: string]: Value } // v11 (deprecated) - all keys are optional HashMap // { [key: string]?: Value } ``` -------------------------------- ### Environment-Based Config Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Loads configuration settings from environment variables such as `TS_RS_EXPORT_DIR`, `TS_RS_LARGE_INT`, and `TS_RS_IMPORT_EXTENSION`. ```rust use ts_rs::{TS, Config}; // Reads TS_RS_EXPORT_DIR, TS_RS_LARGE_INT, TS_RS_IMPORT_EXTENSION let config = Config::from_env(); MyType::export_all(&config)?; ``` -------------------------------- ### Visit Method Signature Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md The signature of the visit method within the TypeVisitor trait. ```rust fn visit(&mut self); ``` -------------------------------- ### Set Output Directory Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/config.md Specifies the directory where TypeScript bindings will be exported. This affects `TS::export()`, `TS::export_all()`, and automatic exports during `cargo test`. ```rust use ts_rs::Config; let config = Config::new() .with_out_dir("./src/types"); assert_eq!(config.out_dir().to_str(), Some("./src/types")); ``` -------------------------------- ### Exporting a Single Rust Type to TypeScript Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/quick-reference.md Demonstrates exporting a single Rust struct (`User`) to a TypeScript file using `export` with a default configuration. ```rust use ts_rs::{TS, Config}; #[derive(TS)] struct User { id: i32, } User::export(&Config::new())?; ``` -------------------------------- ### Setting Export Directory via Build Script Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/advanced-usage.md Configures the output directory for type bindings during the Cargo build process by setting an environment variable. This snippet is intended for use in a `build.rs` file. ```rust // build.rs use std::env; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); println!("cargo:env=TS_RS_EXPORT_DIR={}/bindings", out_dir); } ``` -------------------------------- ### Rust Function Signature: visit_dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md This is a function signature for `visit_dependencies`. It takes a mutable reference to a `TypeVisitor` and iterates over all dependencies of the current type. This is called internally to recursively resolve and export all types used by this type. ```rust fn visit_dependencies(_: &mut impl TypeVisitor) where Self: 'static, ``` -------------------------------- ### Add tokio-impl Dependency Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/types.md Enable the `tokio-impl` feature to integrate `ts-rs` with tokio synchronization types. ```rust [dependencies] ts-rs = { version = "12.0", features = ["tokio-impl"] } tokio = "1.0" ``` -------------------------------- ### Custom Implementation: Dependency Counter Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/type-visitor.md A custom implementation of TypeVisitor to count the number of dependencies a type has. This can be used for static analysis. ```rust use ts_rs::{TS, TypeVisitor, Config}; // Count how many dependencies a type has struct Counter { count: usize, } impl TypeVisitor for Counter { fn visit(&mut self) { self.count += 1; } } ``` -------------------------------- ### dependencies Source: https://github.com/aleph-alpha/ts-rs/blob/main/_autodocs/api-reference/ts-trait.md Recursively resolves and returns a list of all dependencies for the current type. Each dependency is represented as a `Dependency` struct containing its type ID, TypeScript name, and export path. ```APIDOC ## dependencies ### Description Recursively resolves all dependencies of this type. Returns a list of `Dependency` structures containing type ID, TypeScript name, and export path. ### Signature ```rust fn dependencies(cfg: &Config) where Self: 'static, ``` ### Parameters #### Path Parameters - **cfg** (`&Config`) - Required - Configuration affecting type generation. ### Returns Vector of `Dependency` structs. ### Example ```rust use ts_rs::{TS, Config}; let cfg = Config::new(); let deps = User::dependencies(&cfg); for dep in deps { println!("Type: {}, Path: {}", dep.ts_name, dep.output_path.display()); } ``` ```