Tsify is a library for generating TypeScript definitions from Rust code.
Using this with wasm-bindgen
will automatically output the types to .d.ts
.
Inspired by typescript-definitions
and ts-rs
.
Click to show Cargo.toml.
toml
[dependencies]
tsify = "0.3"
serde = { version = "1.0", features = ["derive"] }
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
```rust use serde::{Deserialize, Serialize}; use tsify::Tsify; use wasm_bindgen::prelude::*;
pub struct Point { x: i32, y: i32, }
pub fn into_js() -> Point { Point { x: 0, y: 0 } }
pub fn from_js(point: Point) {} ```
Will generate the following .d.ts
file:
ts
/* tslint:disable */
/* eslint-disable */
/**
* @returns {Point}
*/
export function into_js(): Point;
/**
* @param {Point} point
*/
export function from_js(point: Point): void;
export interface Point {
x: number;
y: number;
}
Tsify container attributes
into_wasm_abi
implements IntoWasmAbi
and OptionIntoWasmAbi
. This can be converted directly from Rust to JS via JSON.from_wasm_abi
implements FromWasmAbi
and OptionFromWasmAbi
. This is the opposite operation of the above.Tsify field attributes
type
optional
Serde attributes
rename
rename-all
tag
content
untagged
skip
skip_serializing
skip_deserializing
skip_serializing_if = "Option::is_none"
flatten
default
transparent
```rust use tsify::Tsify;
pub struct Foo { #[tsify(type = "0 | 1 | 2")] x: i32, } ```
Generated type:
ts
export interface Foo {
x: 0 | 1 | 2;
}
```rust
struct Optional {
#[tsify(optional)]
a: Option
Generated type:
ts
export interface Optional {
a?: number;
b?: string;
c?: number;
}
```rust use tsify::Tsify;
enum Color { Red, Blue, Green, Rgb(u8, u8, u8), Hsv { hue: f64, saturation: f64, value: f64, }, } ```
Generated type:
```ts declare namespace Color { export type Red = "Red"; export type Blue = "Blue"; export type Green = "Green"; export type Rgb = { Rgb: [number, number, number] }; export type Hsv = { Hsv: { hue: number; saturation: number; value: number } }; }
export type Color = | Color.Red | Color.Blue | Color.Green | Color.Rgb | Color.Hsv; ```
```rust use tsify::{declare, Tsify};
struct Foo
type Bar = Foo
Generated type:
ts
export type Foo<T> = T;
export type Bar = Foo<number>;
wasm-bindgen-impl
(default) Generate
typescript_custom_section
and
Rust Type conversions