Model validation and serialization
Speakeasy TypeScript SDKs support model validation and serialization backed by Zod. This feature allows you to validate data against your models and easily serialize or deserialize data to and from JSON.
Example
As an example, consider the following model definition:
<sdk-root>/src/models/components/book.ts
import * as z from "zod";export type Book = {/*** The unique identifier for the book*/id: string;/*** The title of the book*/title: string;/*** The author of the book*/author: string;};
From JSON
example.ts
import { bookFromJSON, bookToJSON } from "my-sdk/models/components/book";const result = bookFromJSON('{"id":"1","title":"1984","author":"George Orwell"}');if (result.ok) {console.log(result.value);// 👆 result.value is of type `Book`} else {// Handle validation errorsconsole.error(result.error);}
To JSON
example.ts
const jsonString = bookToJSON({ id: "1", title: "1984", author: "George Orwell" });// jsonString is of type `string`