Skip to content

Commit

Permalink
Problem: Beginners struggle with recent changes
Browse files Browse the repository at this point in the history
Solution:

 - Port the old example that just exports one type.
 - Add an example which exports everything to a file (which seems to be the go-to way beginners use specta).
  • Loading branch information
cognivore committed Jan 27, 2025
1 parent 5758221 commit 365c8cc
Showing 1 changed file with 49 additions and 6 deletions.
55 changes: 49 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,23 +39,23 @@ cargo add specta --features typescript # only 'typescript' is currently supporte
Then you can use Specta like so:

```rust
use specta::{ts, Type};
use specta::Typescript;

#[derive(Type)]
#[derive(specta::Type)]
pub struct TypeOne {
pub a: String,
pub b: GenericType<i32>,
#[serde(rename = "cccccc")]
pub c: MyEnum,
}

#[derive(Type)]
#[derive(specta::Type)]
pub struct GenericType<A> {
pub my_field: String,
pub generic: A,
}

#[derive(Type)]
#[derive(specta::Type)]
pub enum MyEnum {
A,
B,
Expand All @@ -64,14 +64,57 @@ pub enum MyEnum {

fn main() {
assert_eq!(
ts::export::<TypeOne>(&Default::default()).unwrap(),
specta_typescript::export::<TypeOne>(&Typescript::default()).unwrap(),
"export type TypeOne = { a: string; b: GenericType<number>; cccccc: MyEnum }".to_string()
);
}
```

Check out the [docs](https://docs.rs/specta) for more information.
A common use case is to export all types for which `specta::Type` is derived into a single file:

```rust
use specta::Typescript;

#[derive(specta::Type)]
pub enum MyEither<L, R> {
Left(L),
Right(R),
}

#[derive(specta::Type)]
pub struct GenericType<A> {
pub my_field: String,
pub generic: A,
}

#[derive(specta::Type)]
pub enum MyEnum {
A,
B,
C,
}

fn main() {
let types_path = std::path::Path::new("priv/test/types.ts");
Typescript::default().export_to(types_path, &specta::export()).unwrap();
}
```

This code shall generate the following file and create `priv/test` if it doesn't exist:

```typescript
// This file has been generated by Specta. DO NOT EDIT.

export type GenericType<A> = { my_field: string; generic: A }

export type MyEither<L, R> = { Left: L } | { Right: R }

export type MyEnum = "A" | "B" | "C"

export type TypeOne = { a: string; b: GenericType<number>; cccccc: MyEnum }
```
Check out the [docs](https://docs.rs/specta) for more information.
## Motivation
Expand Down

0 comments on commit 365c8cc

Please sign in to comment.