7 releases

0.2.2 Feb 20, 2022
0.2.1 Feb 20, 2022
0.2.0 Jan 21, 2022
0.1.3 Jan 16, 2022

#217 in FFI

MIT license

18KB
276 lines

ts2rs

A proc-macro library that imports Typescript interface definitions into Rust.

Usage

See docs.rs

Todo list

  • Better error reporting;
  • Import from class definitions;
  • Advanced types like date and time;

lib.rs:

githubcrates-iodocs-rs


This crate provides the import! macro for importing Typescript interfaces into Rust.

Type Mappings

For now, only primitive types are supported, with the following mapping:

Typescript Type Rust Type
string String
number f64
boolean bool
T[] Vec<T>
T? Option<T>
any user-defined type/interface a struct definition(first letter capitalized)

Usage

See the import! macro.

Cargo Features

serde

By default, all interfaces are imported as structs that only derive Debug.

Enabling this feature will make all structs derive serde::Serialize and serde::Deserialize by default.

For more derive options, check out the derive option.

Import Options

Use comments that start with /** and end with **/ to specify options for the import. Multiple options can reside in the same comment block, each ending with a semicolon ;.

Rename

Use /** rename: <name>; **/ to rename the field/interface to <name>.

Example

interface Fries {
  favorite: boolean; /** rename: favourite; **/
  price: number;
} /** rename: Chips; **/

This would result in the following struct definition:

#[derive(Debug)]
pub struct Chips {
  favourite: bool,
  price: f64,
}

Retype

Use /** retype: <type>; **/ to retype the field to <type>.

Example

interface Chocolate {
  price: number; /** retype: i32; **/
}

This would result in the following struct definition:

#[derive(Debug)]
pub struct Chocolate {
  price: i32,
}

Skip

Use /** skip; **/ to skip the field/interface.

Example

interface User {
  id: number;
  theme: string; /** skip; **/ // backend doesn't care about this field
}
interface Advertisement {
  id: number;
  url: string;
} /** skip; **/ // backend doesn't care about this interface

This would result in the following struct definition:

#[derive(Debug)]
pub struct User {
  id: f64,
}

Derive

Use /** derive: <derive>; **/ to derive a trait for the interface.

Example

interface User {
  id: number;
} /** derive: PartialEq; derive: Eq; **/

This would result in the following struct definition:

#[derive(Debug, PartialEq, Eq)]
pub struct User {
  id: f64,
}

Skip Derive Serde

Use /** skip_derive_serde; **/ to skip the serde derives for the interface.

Example

interface User {
  id: number;
} /** skip_derive_serde; **/

This would result in the following struct definition:

#[derive(Debug)]
pub struct User {
  id: f64,
}

Dependencies

~2.1–2.9MB
~57K SLoC