Skip to content

typed-schemaTypeScript-first Sanity schemas

Declare a content model once. Get its TypeScript types and a runtime validator from the same definition.

ts
import * as 
s
from '@sanity-labs/typed-schema'
export const
Recipe
=
s
.
document
({
_type
:
s
.
literal
('recipe'),
title
:
s
.
string
(),
servings
:
s
.
optional
(
s
.
number
()),
}) export type
Recipe
=
s
.
Infer
<typeof
Recipe
>
const
result
=
s
.
parse
(
Recipe
, await
client
.
fetch
('*[_type == "recipe"][0]'))
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;
}
} else { // for a recipe without a title and with "four" as servings: // Invalid input (2 issues): // title: Expected a string // servings: Expected a finite number
console
.
error
(
result
.
error
.
message
)
}