Skip to content

Frequently Asked Questions

Moritz Bischof edited this page Mar 16, 2024 · 1 revision

What do I do if a type does not implement TS?

First, check if there's a cargo feature to enable support for the type in the README.

If there's no such feature, and the type is relatively simple, you can use #[ts(type = "number")] to manually specify a TypeScript type for the field.

However, for more complex types, that solution doesn't scale well. Instead, you can write an equivalent type and use #[ts(as = "..")]:

#[derive(TS)]
struct ForeignType {
    something: i32,
}

#[derive(TS)]
struct MyType {
    #[ts(as = "ForeignType")]
    foreign: foreign::Type,
}

Finally, you can open an issue or PR to add support for that type, gated behind a cargo feature.

Can I use ts-rs in libraries?

Yes!
Consumers of your library will then get a copy of the TypeScript definition of your types when they export theirs.

We recommend that you namespace your types using #[ts(export_to = "my_library/")] to avoid name collisions.

Can ts-rs handle associated types?

Yes!
However, TypeScript has no concept of associated types. Therefore, ts-rs cannot generate a generic TypeScript definition for types containing associated types.

To work around this, ts-rs can generate a non-generic ("concrete") type instead.
To make this work, you have to specify a type for the type parameter which is to be used to generate bindings.

Example:

trait MyTrait {
   type Item;
}

struct DefaultType;
impl MyTrait for DefaultType {
   type Item = i32;
}

#[derive(TS)]
#[ts(concrete(I = DefaultType))]
struct MyType<I: MyTrait> {
    item: I::Item
}