A Rust crate for generating TypeScript bindings from structs.
cargo add ts-bindAdd the following to your Rust code:
use ts_bind::TsBind;
#[derive(TsBind)]
struct MyStruct {
field1: String,
field2: i32,
}This will generate the corresponding TypeScript interface in the bindings directory.
// bindings/MyStruct.ts
export interface MyStruct {
field1: string;
field2: number;
}You can rename the generated interface by adding the #[ts_bind(rename = "NewName")] attribute.
#[derive(TsBind)]
#[ts_bind(rename = "NewName")]
struct MyStruct {
field1: String,
field2: i32,
}// bindings/NewName.ts
export interface NewName {
field1: string;
field2: number;
}You can rename all fields by case by adding the #[ts_bind(rename_all = "...")] attribute.
#[derive(TsBind)]
#[ts_bind(rename_all = "camelCase")]
struct MyStruct {
field_one: String,
field_two: i32,
}// bindings/MyStruct.ts
export interface MyStruct {
fieldOne: string;
fieldTwo: number;
}You can specify a custom export path by adding the #[ts_bind(export = "path/to/export")] attribute.
#[derive(TsBind)]
#[ts_bind(export = "models")]
struct MyStruct {
field1: String,
field2: i32,
}// models/MyStruct.ts
export interface MyStruct {
field1: string;
field2: number;
}Unknown types will automatically be imported to the output TypeScript file.
#[derive(TsBind)]
struct User {
id: i32,
posts: Vec<Post>,
}
#[derive(TsBind)]
struct Post {
title: String,
}// bindings/User.ts
import { Post } from "./Post"; // automatically imported
export interface User {
id: number;
posts: Post[];
}
// bindings/Post.ts
export interface Post {
title: string;
}You can skip fields by adding the #[ts_bind(skip)] attribute.
#[derive(TsBind)]
struct User {
id: i32,
#[ts_bind(skip)]
password: String,
}export interface User {
id: number;
}The ts_bind attribute supports the following optional arguments for the entire struct:
| Argument | Description |
|---|---|
rename |
Rename the generated interface. |
rename_all |
Rename all fields by case. |
export |
Custom export path. |
The ts_bind attribute supports the following optional arguments for individual fields:
| Argument | Description |
|---|---|
rename |
Rename the field. |
skip |
Skip the field. |
#[derive(TsBind)]
struct User {
id: i32,
#[ts_bind(rename = "postCount")]
post_count: i32,
}export interface User {
id: number;
postCount: number;
}The library is far from complete. Here are some of the features that are planned:
-
#[ts_bind(export = "path/to/export")]custom export path. -
#[ts_bind(rename_all = "camelCase")]attribute to rename all fields. -
#[ts_bind(skip)]attribute to skip fields. - Support for enums.
-
#[ts_bind(skip_if = "condition")]attribute to skip fields based on a condition.
Feel free to open issues or submit pull requests on our GitHub repository.
This project is licensed under the MIT License. See the LICENSE file for details.
