@sanity/client with typed GROQ Results
Using.Sanity.Typed.mp4
@[:page_toc](## Page Contents)
npm install sanity @sanity-typed/client
Use createClient
exactly as you would from @sanity/client
.
@typescript @typescript @typescript
Sometimes, you'll have a preconfigured client from a separate library that you will still want typed results from. A castToTyped
function is provided to do just that.
import { createClient } from "some-other-create-client";
import { castToTyped } from "@sanity-typed/client";
import type { SanityValues } from "./sanity.config";
const client = createClient({
// ...
});
const typedClient = castToTyped<SanityValues>()(client);
// Also, if you need the config in the client (eg. for queries using $param),
// you can provide the same config again to include it in the types.
// const typedClient = castToTyped<SanityValues>()(client, {
// ...same contents from createClient
// });
const data = await typedClient.fetch("*");
/**
* typeof data === {
* _createdAt: string;
* _id: string;
* _rev: string;
* _type: "product";
* _updatedAt: string;
* productName?: string;
* tags?: {
* _key: string;
* label?: string;
* value?: string;
* }[];
* }[]
*/
This function (nor the createClient
function) have any runtime implications; it passes through the initial client unaltered.
Similarly, if you have a typed client that you want to untype (presumably to export from a library for general consumption), you can always cast it:
import type { SanityClient as SanityClientNative } from "@sanity/client";
import { createClient } from "@sanity-typed/client";
import type { SanityValues } from "./sanity.config";
const client = createClient<SanityValues>({
// ...
});
export const typedClient = client;
export const untypedClient = client as SanityClientNative;
export default untypedClient;
@:markdown @:markdown @:markdown @:markdown
The supported Typescript version is now 5.4.2 <= x <= 5.6.3. Older versions are no longer supported and newer versions will be added as we validate it.
Removing the double function signature from createClient
:
- const client = createClient<SanityValues>()({
+ const client = createClient<SanityValues>({
// ...
});
We no longer derive types from your config values. Most of the types weren't significant, but the main loss will be _originalId
when the perspective
was "previewDrafts"
.
Casting from typed to untyped is now just a simple cast:
+ import type { SanityClient as SanityClientNative } from "@sanity/client";
- import { castFromTyped, createClient } from "@sanity-typed/client";
+ import { createClient } from "@sanity-typed/client";
import type { SanityValues } from "./sanity.config";
const client = createClient<SanityValues>()({
// ...
});
export const typedClient = client;
- export const untypedClient = castFromTyped(client);
+ export const untypedClient = client as SanityClientNative;
export default untypedClient;
castToTyped
still exists.