Skip to content

Getting started ​

Requires TypeScript 6.0 or later with strict: true in tsconfig.json.

sh
npm install @sanity-labs/typed-schema
sh
pnpm add @sanity-labs/typed-schema
sh
yarn add @sanity-labs/typed-schema
sh
bun add @sanity-labs/typed-schema

The package is published as ES modules only.

A first schema ​

The examples on this site import the package as a namespace, import * as s from '@sanity-labs/typed-schema', so creators read as s.document(), s.string() and so on. Named imports work just as well.

Every schema is a value built from creator functions. Infer turns a schema into its TypeScript type, and parse checks a value against the schema at runtime:

ts
import * as 
s
from '@sanity-labs/typed-schema'
const
Recipe
=
s
.
document
({
_type
:
s
.
literal
('recipe'),
title
:
s
.
string
(),
servings
:
s
.
optional
(
s
.
number
()),
}) type Recipe =
s
.
Infer
<typeof
Recipe
>
type Recipe = {
    _type: "recipe";
    _id?: string | undefined;
    _createdAt?: string | undefined;
    _updatedAt?: string | undefined;
    _rev?: string | undefined;
    title: string;
    servings?: number | undefined;
}
const
response
= await
fetch
('https://example.com/recipes/pancakes.json')
const
result
=
s
.
parse
(
Recipe
, await
response
.
json
())
if (
result
.
ok
) {
const recipe =
result
.
value
const recipe: {
    _type: "recipe";
    _id?: string | undefined;
    _createdAt?: string | undefined;
    _updatedAt?: string | undefined;
    _rev?: string | undefined;
    title: string;
    servings?: number | undefined;
}
}

Hover any name in the examples on this site to see its type. To try your own schemas, open the playground.

Next steps ​