@sanity-typed/groq
Infer GROQ Result Types from GROQ strings
Page Contents
Install
npm install @sanity-typed/groq
Usage
Typically, this isn't used directly, but via @sanity-typed/client
's and @sanity-typed/groq-js
's methods that use groq strings. But it can be done directly:
import { ExecuteQuery, RootScope } from "@sanity-typed/groq";
type Foo = ExecuteQuery<
'*[_type=="foo"]',
RootScope<
// If you have SanityValues from @sanity-typed/types, use those types:
// import { DocumentValues } from "@sanity-typed/types";
// DocumentValues<SanityValues>
({ _type: "bar" } | { _type: "foo" })[],
{ _type: "bar" } | { _type: "foo" }
>
>;
/**
* Foo === {
* _type: "foo";
* }[]
*/
There is also a Parse
and Evaluate
if you need the AST:
import { Evaluate, Parse, RootScope } from "@sanity-typed/groq";
type Tree = Parse<'*[_type=="foo"]'>;
/**
* Tree === {
* type: "Filter";
* base: { type: "Everything" };
* expr: {
* type: "OpCall";
* op: "==";
* left: { type: "AccessAttribute"; name: "_type" };
* right: { type: "Value"; value: "foo" };
* };
* }
*/
type Foo = Evaluate<
Tree,
RootScope<
// If you have SanityValues from @sanity-typed/types, use those types:
// import { DocumentValues } from "@sanity-typed/types";
// DocumentValues<SanityValues>
({ _type: "bar" } | { _type: "foo" })[],
{ _type: "bar" } | { _type: "foo" }
>
>;
/**
* Foo === {
* _type: "foo";
* }[]
*/
For either, you can pass in a full scope:
import { ExecuteQuery } from "@sanity-typed/groq";
type Foo = ExecuteQuery<
'*[_type=="foo"]',
{
context: {
client: ClientConfig;
dataset: ({ _type: "bar" } | { _type: "foo" })[];
delta:
| {
after: { _type: "bar" } | null;
before: { _type: "bar" } | null;
}
| {
after: { _type: "foo" } | null;
before: { _type: "foo" } | null;
};
identity: string;
parameters: { [param: string]: any };
};
parent: null;
this: null;
}
>;
Chances are, you don't need this package directly.
Considerations
The parsed tree changes in seemingly breaking ways
@sanity-typed/groq
attempts to type its parsed types as close as possible to groq-js
's parse
function output. Any fixes to match it more correctly won't be considered a major change and, if groq-js
changes it's output in a version update, we're likely to match it. If you're using the parsed tree's types directly, this might cause your code to break. We don't consider this a breaking change because the intent of these groq libraries is to match the types of a groq query as closely as possible.