Trait ts_rs::TS

source ·
pub trait TS {
    type WithoutGenerics: TS + ?Sized;

    const DOCS: Option<&'static str> = None;
Show 15 methods // Required methods fn decl() -> String; fn decl_concrete() -> String; fn name() -> String; fn inline() -> String; fn inline_flattened() -> String; // Provided methods fn ident() -> String { ... } fn dependency_types() -> impl TypeList where Self: 'static { ... } fn generics() -> impl TypeList where Self: 'static { ... } fn dependencies() -> Vec<Dependency> where Self: 'static { ... } fn export() -> Result<(), ExportError> where Self: 'static { ... } fn export_all() -> Result<(), ExportError> where Self: 'static { ... } fn export_all_to(out_dir: impl AsRef<Path>) -> Result<(), ExportError> where Self: 'static { ... } fn export_to_string() -> Result<String, ExportError> where Self: 'static { ... } fn output_path() -> Option<&'static Path> { ... } fn default_output_path() -> Option<PathBuf> { ... }
}
Expand description

A type which can be represented in TypeScript.
Most of the time, you’d want to derive this trait instead of implementing it manually.
ts-rs comes with implementations for all primitives, most collections, tuples, arrays and containers.

§exporting

Because Rusts procedural macros are evaluated before other compilation steps, TypeScript bindings cannot be exported during compile time.

Bindings can be exported within a test, which ts-rs generates for you by adding #[ts(export)] to a type you wish to export to a file.
When cargo test is run, all types annotated with #[ts(export)] and all of their dependencies will be written to TS_RS_EXPORT_DIR, or ./bindings by default.

For each individual type, path and filename within the output directory can be changed using #[ts(export_to = "...")]. By default, the filename will be derived from the name of the type.

If, for some reason, you need to do this during runtime or cannot use #[ts(export)], bindings can be exported manually:

FunctionIncludes DependenciesTo
TS::exportTS_RS_EXPORT_DIR
TS::export_all✔️TS_RS_EXPORT_DIR
TS::export_all_to✔️custom

§serde compatibility

By default, the feature serde-compat is enabled. ts-rs then parses serde attributes and adjusts the generated typescript bindings accordingly. Not all serde attributes are supported yet - if you use an unsupported attribute, you’ll see a warning.

§container attributes

attributes applicable for both structs and enums

  • #[ts(crate = "..")] Generates code which references the module passed to it instead of defaulting to ::ts_rs This is useful for cases where you have to re-export the crate.

  • #[ts(export)]
    Generates a test which will export the type, by default to bindings/<name>.ts when running cargo test. The default base directory can be overridden with the TS_RS_EXPORT_DIR environment variable. Adding the variable to a project’s config.toml can make it easier to manage.

    # <project-root>/.cargo/config.toml
    [env]
    TS_RS_EXPORT_DIR = { value = "<OVERRIDE_DIR>", relative = true }
    

  • #[ts(export_to = "..")]
    Specifies where the type should be exported to. Defaults to <name>.ts.
    The path given to the export_to attribute is relative to the TS_RS_EXPORT_DIR environment variable, or, if TS_RS_EXPORT_DIR is not set, to ./bindings
    If the provided path ends in a trailing /, it is interpreted as a directory.
    Note that you need to add the export attribute as well, in order to generate a test which exports the type.

  • #[ts(rename = "..")]
    Sets the typescript name of the generated type

  • #[ts(rename_all = "..")]
    Rename all fields/variants of the type.
    Valid values are lowercase, UPPERCASE, camelCase, snake_case, PascalCase, SCREAMING_SNAKE_CASE, “kebab-case”

  • #[ts(concrete(..)]
    Disables one ore more generic type parameters by specifying a concrete type for them.
    The resulting TypeScript definition will not be generic over these parameters and will use the provided type instead.
    This is especially useful for generic types containing associated types. Since TypeScript does not have an equivalent construct to associated types, we cannot generate a generic definition for them. Using #[ts(concrete(..)], we can however generate a non-generic definition. Example:

    #[derive(TS)]
    #[ts(concrete(I = std::vec::IntoIter<String>))]
    struct SearchResult<I: Iterator>(Vec<I::Item>);
    // will always generate `type SearchResult = Array<String>`.



  • #[ts(bound)] Override the bounds generated on the TS implementation for this type. This is useful in combination with #[ts(concrete)], when the type’s generic parameters aren’t directly used in a field or variant.

    Example:

    
    trait Container {
        type Value: TS;
    }
    
    struct MyContainer;
    
    #[derive(TS)]
    struct MyValue;
    
    impl Container for MyContainer {
        type Value = MyValue;
    }
    
    #[derive(TS)]
    #[ts(export, concrete(C = MyContainer))]
    struct Inner<C: Container> {
        value: C::Value,
    }
    
    #[derive(TS)]
    // Without `#[ts(bound)]`, `#[derive(TS)]` would generate an unnecessary
    // `C: TS` bound
    #[ts(export, concrete(C = MyContainer), bound = "C::Value: TS")]
    struct Outer<C: Container> {
        inner: Inner<C>,
    }



§struct attributes

  • #[ts(tag = "..")]
    Include the structs name (or value of #[ts(rename = "..")]) as a field with the given key.

§struct field attributes

  • #[ts(type = "..")]
    Overrides the type used in TypeScript.
    This is useful when there’s a type for which you cannot derive TS.

  • #[ts(as = "..")]
    Overrides the type of the annotated field, using the provided Rust type instead. This is useful when there’s a type for which you cannot derive TS.

  • #[ts(rename = "..")]
    Renames this field. To rename all fields of a struct, see the container attribute #[ts(rename_all = "..")].

  • #[ts(inline)]
    Inlines the type of this field, replacing its name with its definition.

  • #[ts(skip)]
    Skips this field, omitting it from the generated TypeScript type.

  • #[ts(optional)]
    May be applied on a struct field of type Option<T>. By default, such a field would turn into t: T | null.
    If #[ts(optional)] is present, t?: T is generated instead.
    If #[ts(optional = nullable)] is present, t?: T | null is generated.

  • #[ts(flatten)]
    Flatten this field, inlining all the keys of the field’s type into its parent.

§enum attributes

  • #[ts(tag = "..")]
    Changes the representation of the enum to store its tag in a separate field.
    See the serde docs for more information.

  • #[ts(content = "..")]
    Changes the representation of the enum to store its content in a separate field.
    See the serde docs for more information.

  • #[ts(untagged)]
    Changes the representation of the enum to not include its tag.
    See the serde docs for more information.

  • #[ts(rename_all = "..")]
    Rename all variants of this enum.
    Valid values are lowercase, UPPERCASE, camelCase, snake_case, PascalCase, SCREAMING_SNAKE_CASE, “kebab-case”

  • #[ts(rename_all_fieds = "..")]
    Renames the fields of all the struct variants of this enum. This is equivalent to using #[ts(rename_all = "..")] on all of the enum’s variants. Valid values are lowercase, UPPERCASE, camelCase, snake_case, PascalCase, SCREAMING_SNAKE_CASE, “kebab-case”

§enum variant attributes

  • #[ts(rename = "..")]
    Renames this variant. To rename all variants of an enum, see the container attribute #[ts(rename_all = "..")].

  • #[ts(skip)]
    Skip this variant, omitting it from the generated TypeScript type.

  • #[ts(untagged)]
    Changes this variant to be treated as if the enum was untagged, regardless of the enum’s tag and content attributes

  • #[ts(rename_all = "..")]
    Renames all the fields of a struct variant. Valid values are lowercase, UPPERCASE, camelCase, snake_case, PascalCase, SCREAMING_SNAKE_CASE, “kebab-case”

Required Associated Types§

source

type WithoutGenerics: TS + ?Sized

If this type does not have generic parameters, then WithoutGenerics should just be Self. If the type does have generic parameters, then all generic parameters must be replaced with a dummy type, e.g ts_rs::Dummy or (). The only requirement for these dummy types is that EXPORT_TO must be None.

§Example:
use ts_rs::TS;
struct GenericType<A, B>(A, B);
impl<A, B> TS for GenericType<A, B> {
    type WithoutGenerics = GenericType<ts_rs::Dummy, ts_rs::Dummy>;
    // ...
}

Provided Associated Constants§

source

const DOCS: Option<&'static str> = None

JSDoc comment to describe this type in TypeScript - when TS is derived, docs are automatically read from your doc comments or #[doc = ".."] attributes

Required Methods§

source

fn decl() -> String

Declaration of this type, e.g. type User = { user_id: number, ... }. This function will panic if the type has no declaration.

If this type is generic, then all provided generic parameters will be swapped for placeholders, resulting in a generic typescript definition. Both SomeType::<i32>::decl() and SomeType::<String>::decl() will therefore result in the same TypeScript declaration type SomeType<A> = ....

source

fn decl_concrete() -> String

Declaration of this type using the supplied generic arguments. The resulting TypeScript definition will not be generic. For that, see TS::decl(). If this type is not generic, then this function is equivalent to TS::decl().

source

fn name() -> String

Name of this type in TypeScript, including generic parameters

source

fn inline() -> String

Formats this types definition in TypeScript, e.g { user_id: number }. This function will panic if the type cannot be inlined.

source

fn inline_flattened() -> String

Flatten an type declaration.
This function will panic if the type cannot be flattened.

Provided Methods§

source

fn ident() -> String

Identifier of this type, excluding generic parameters.

source

fn dependency_types() -> impl TypeList
where Self: 'static,

Returns a TypeList of all types on which this type depends.

source

fn generics() -> impl TypeList
where Self: 'static,

Returns a TypeList containing all generic parameters of this type. If this type is not generic, this will return an empty TypeList.

source

fn dependencies() -> Vec<Dependency>
where Self: 'static,

Resolves all dependencies of this type recursively.

source

fn export() -> Result<(), ExportError>
where Self: 'static,

Manually export this type to the filesystem. To export this type together with all of its dependencies, use TS::export_all.

§Automatic Exporting

Types annotated with #[ts(export)], together with all of their dependencies, will be exported automatically whenever cargo test is run.
In that case, there is no need to manually call this function.

§Target Directory

The target directory to which the type will be exported may be changed by setting the TS_RS_EXPORT_DIR environment variable. By default, ./bindings will be used.

To specify a target directory manually, use TS::export_all_to, which also exports all dependencies.

To alter the filename or path of the type within the target directory, use #[ts(export_to = "...")].

source

fn export_all() -> Result<(), ExportError>
where Self: 'static,

Manually export this type to the filesystem, together with all of its dependencies.
To export only this type, without its dependencies, use TS::export.

§Automatic Exporting

Types annotated with #[ts(export)], together with all of their dependencies, will be exported automatically whenever cargo test is run.
In that case, there is no need to manually call this function.

§Target Directory

The target directory to which the types will be exported may be changed by setting the TS_RS_EXPORT_DIR environment variable. By default, ./bindings will be used.

To specify a target directory manually, use TS::export_all_to.

To alter the filenames or paths of the types within the target directory, use #[ts(export_to = "...")].

source

fn export_all_to(out_dir: impl AsRef<Path>) -> Result<(), ExportError>
where Self: 'static,

Manually export this type into the given directory, together with all of its dependencies.
To export only this type, without its dependencies, use TS::export.

Unlike TS::export_all, this function disregards TS_RS_EXPORT_DIR, using the provided directory instead.

To alter the filenames or paths of the types within the target directory, use #[ts(export_to = "...")].

§Automatic Exporting

Types annotated with #[ts(export)], together with all of their dependencies, will be exported automatically whenever cargo test is run.
In that case, there is no need to manually call this function.

source

fn export_to_string() -> Result<String, ExportError>
where Self: 'static,

Manually generate bindings for this type, returning a String.
This function does not format the output, even if the format feature is enabled. TODO

§Automatic Exporting

Types annotated with #[ts(export)], together with all of their dependencies, will be exported automatically whenever cargo test is run.
In that case, there is no need to manually call this function.

source

fn output_path() -> Option<&'static Path>

Returns the output path to where T should be exported.
The returned path does not include the base directory from TS_RS_EXPORT_DIR.

To get the output path containing TS_RS_EXPORT_DIR, use TS::default_output_path.

When deriving TS, the output path can be altered using #[ts(export_to = "...")].
See the documentation of TS for more details.

The output of this function depends on the environment variable TS_RS_EXPORT_DIR, which is used as base directory. If it is not set, ./bindings is used as default directory.

If T cannot be exported (e.g because it’s a primitive type), this function will return None.

source

fn default_output_path() -> Option<PathBuf>

Returns the output path to where T should be exported.

The output of this function depends on the environment variable TS_RS_EXPORT_DIR, which is used as base directory. If it is not set, ./bindings is used as default directory.

To get the output path relative to TS_RS_EXPORT_DIR and without reading the environment variable, use TS::output_path.

When deriving TS, the output path can be altered using #[ts(export_to = "...")].
See the documentation of TS for more details.

If T cannot be exported (e.g because it’s a primitive type), this function will return None.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl TS for IpAddr

source§

impl TS for SocketAddr

source§

impl TS for bool

source§

impl TS for char

source§

impl TS for f32

source§

impl TS for f64

source§

impl TS for i8

source§

impl TS for i16

source§

impl TS for i32

source§

impl TS for i64

source§

impl TS for i128

source§

impl TS for isize

source§

impl TS for str

source§

impl TS for u8

source§

impl TS for u16

source§

impl TS for u32

source§

impl TS for u64

source§

impl TS for u128

source§

impl TS for ()

source§

impl TS for usize

source§

impl TS for String

source§

impl TS for Ipv4Addr

source§

impl TS for Ipv6Addr

source§

impl TS for SocketAddrV4

source§

impl TS for SocketAddrV6

source§

impl TS for Path

source§

impl TS for PathBuf

source§

impl TS for NonZeroI8

source§

impl TS for NonZeroI16

source§

impl TS for NonZeroI32

source§

impl TS for NonZeroI64

source§

impl TS for NonZeroI128

source§

impl TS for NonZeroIsize

source§

impl TS for NonZeroU8

source§

impl TS for NonZeroU16

source§

impl TS for NonZeroU32

source§

impl TS for NonZeroU64

source§

impl TS for NonZeroU128

source§

impl TS for NonZeroUsize

source§

impl<'a, T: TS + ToOwned + ?Sized> TS for Cow<'a, T>

§

type WithoutGenerics = Cow<'a, T>

source§

fn name() -> String

source§

fn inline() -> String

source§

fn inline_flattened() -> String

source§

fn dependency_types() -> impl TypeList
where Self: 'static,

source§

fn generics() -> impl TypeList
where Self: 'static,

source§

fn decl() -> String

source§

fn decl_concrete() -> String

source§

impl<I: TS> TS for Range<I>

§

type WithoutGenerics = Range<Dummy>

source§

fn name() -> String

source§

fn dependency_types() -> impl TypeList
where Self: 'static,

source§

fn generics() -> impl TypeList
where Self: 'static,

source§

fn decl() -> String

source§

fn decl_concrete() -> String

source§

fn inline() -> String

source§

fn inline_flattened() -> String

source§

impl<I: TS> TS for RangeInclusive<I>

source§

impl<K: TS, V: TS> TS for BTreeMap<K, V>

source§

impl<K: TS, V: TS, H> TS for HashMap<K, V, H>

§

type WithoutGenerics = HashMap<Dummy, Dummy>

source§

fn ident() -> String

source§

fn name() -> String

source§

fn inline() -> String

source§

fn dependency_types() -> impl TypeList
where Self: 'static,

source§

fn generics() -> impl TypeList
where Self: 'static,

source§

fn decl() -> String

source§

fn decl_concrete() -> String

source§

fn inline_flattened() -> String

source§

impl<T1: TS, T2: TS, T3: TS, T4: TS, T5: TS, T6: TS, T7: TS, T8: TS, T9: TS, T10: TS> TS for (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)

source§

impl<T2: TS, T3: TS, T4: TS, T5: TS, T6: TS, T7: TS, T8: TS, T9: TS, T10: TS> TS for (T2, T3, T4, T5, T6, T7, T8, T9, T10)

source§

impl<T3: TS, T4: TS, T5: TS, T6: TS, T7: TS, T8: TS, T9: TS, T10: TS> TS for (T3, T4, T5, T6, T7, T8, T9, T10)

source§

impl<T4: TS, T5: TS, T6: TS, T7: TS, T8: TS, T9: TS, T10: TS> TS for (T4, T5, T6, T7, T8, T9, T10)

source§

impl<T5: TS, T6: TS, T7: TS, T8: TS, T9: TS, T10: TS> TS for (T5, T6, T7, T8, T9, T10)

source§

impl<T6: TS, T7: TS, T8: TS, T9: TS, T10: TS> TS for (T6, T7, T8, T9, T10)

source§

impl<T7: TS, T8: TS, T9: TS, T10: TS> TS for (T7, T8, T9, T10)

source§

impl<T8: TS, T9: TS, T10: TS> TS for (T8, T9, T10)

source§

impl<T9: TS, T10: TS> TS for (T9, T10)

source§

impl<T10: TS> TS for (T10,)

source§

impl<T: TS + ?Sized> TS for &T

source§

impl<T: TS + ?Sized> TS for Box<T>

source§

impl<T: TS + ?Sized> TS for Rc<T>

source§

impl<T: TS + ?Sized> TS for Arc<T>

source§

impl<T: TS + ?Sized> TS for Weak<T>

source§

impl<T: TS> TS for Option<T>

source§

impl<T: TS> TS for [T]

source§

impl<T: TS> TS for BTreeSet<T>

source§

impl<T: TS> TS for Vec<T>

source§

impl<T: TS> TS for Cell<T>

source§

impl<T: TS> TS for RefCell<T>

source§

impl<T: TS> TS for PhantomData<T>

source§

impl<T: TS> TS for Mutex<T>

source§

impl<T: TS, E: TS> TS for Result<T, E>

§

type WithoutGenerics = Result<Dummy, Dummy>

source§

fn name() -> String

source§

fn inline() -> String

source§

fn dependency_types() -> impl TypeList
where Self: 'static,

source§

fn generics() -> impl TypeList
where Self: 'static,

source§

fn decl() -> String

source§

fn decl_concrete() -> String

source§

fn inline_flattened() -> String

source§

impl<T: TS, H> TS for HashSet<T, H>

source§

impl<T: TS, const N: usize> TS for [T; N]

§

type WithoutGenerics = [Dummy; N]

source§

fn name() -> String

source§

fn inline() -> String

source§

fn dependency_types() -> impl TypeList
where Self: 'static,

source§

fn generics() -> impl TypeList
where Self: 'static,

source§

fn decl() -> String

source§

fn decl_concrete() -> String

source§

fn inline_flattened() -> String

Implementors§