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.
[dependencies]
tsify = "0.4.5"serde = { version = "1.0", features = ["derive"] }
wasm-bindgen = { version = "0.2" }use serde::{Deserialize,Serialize};use tsify::Tsify;use wasm_bindgen::prelude::*;#[derive(Tsify,Serialize,Deserialize)]#[tsify(into_wasm_abi, from_wasm_abi)]pubstructPoint{x:i32,y:i32,}#[wasm_bindgen]pubfninto_js() -> Point{Point{x:0,y:0}}#[wasm_bindgen]pubfnfrom_js(point:Point){}Will generate the following .d.ts file:
/* tslint:disable *//* eslint-disable *//** * @returns {Point} */exportfunctioninto_js(): Point;/** * @param {Point} point */exportfunctionfrom_js(point: Point): void;exportinterfacePoint{x: number;y: number;}This is the behavior due to typescript_custom_section and Rust Type conversions.
json(default) enables serialization throughserde_json.jsenables serialization throughserde-wasm-bindgenand generates the appropriate types for it. This will be the default in future versions.
Tsify container attributes
into_wasm_abiimplementsIntoWasmAbiandOptionIntoWasmAbi. This can be converted directly from Rust to JS viaserde_jsonorserde-wasm-bindgen.from_wasm_abiimplementsFromWasmAbiandOptionFromWasmAbi. This is the opposite operation of the above.namespacegenerates a namespace for the enum variants.
Tsify field attributes
typeoptional
Serde attributes
renamerename-alltagcontentuntaggedskipskip_serializingskip_deserializingskip_serializing_if = "Option::is_none"flattendefaulttransparent
use tsify::Tsify;#[derive(Tsify)]pubstructFoo{#[tsify(type = "0 | 1 | 2")]x:i32,}Generated type:
exportinterfaceFoo{x: 0|1|2;}#[derive(Tsify)]structOptional{#[tsify(optional)]a:Option<i32>,#[serde(skip_serializing_if = "Option::is_none")]b:Option<String>,#[serde(default)]c:i32,}Generated type:
exportinterfaceOptional{a?: number;b?: string;c?: number;}#[derive(Tsify)]enumColor{Red,Blue,Green,Rgb(u8,u8,u8),Hsv{hue:f64,saturation:f64,value:f64,},}Generated type:
exporttypeColor=|"Red"|"Blue"|"Green"|{Rgb: [number,number,number]}|{Hsv: {hue: number;saturation: number;value: number}};#[derive(Tsify)]#[tsify(namespace)]enumColor{Red,Blue,Green,Rgb(u8,u8,u8),Hsv{hue:f64,saturation:f64,value:f64,},}Generated type:
declarenamespaceColor{exporttypeRed="Red";exporttypeBlue="Blue";exporttypeGreen="Green";exporttypeRgb={Rgb: [number,number,number]};exporttypeHsv={Hsv: {hue: number;saturation: number;value: number}};}exporttypeColor=|"Red"|"Blue"|"Green"|{Rgb: [number,number,number]}|{Hsv: {hue: number;saturation: number;value: number}};use tsify::{declare,Tsify};#[derive(Tsify)]structFoo<T>(T);#[declare]typeBar = Foo<i32>;Generated type:
exporttypeFoo<T>=T;exporttypeBar=Foo<number>;