109Cafe

Extract param types from GROQ

DevelopmentOct 4, 2024

This article shows a type helper for extracting parameter types from a GROQ statement.

Type Helper

groq.ts
export type ExtractVariables<T extends string> = T extends `${infer _}$${infer First}${infer Rest}`
  ? First extends ValidStart
    ? // biome-ignore lint/complexity/noBannedTypes: <explanation>
      _MoveCursor<First, Rest, {}>
    : ExtractVariables<`${First}${Rest}`>
  : // biome-ignore lint/complexity/noBannedTypes: <explanation>
    {};

// biome-ignore format: x
type ValidStart = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" |
    "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" |
    "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" |
    "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" |
    "_";

type ValidChar = ValidStart | "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";

type _MoveCursor<
  /* variable part */ Matched extends string,
  /* rest part */ Rest extends string,
  /* result */ Rec extends Record<string, unknown>,
> = Rest extends ""
  ? /* stop */ Rec & { [key in Matched]: unknown }
  : /* cursor */ Rest extends `${infer First}${infer NewRest}`
    ? First extends ValidChar
      ? _MoveCursor<`${Matched}${First}`, NewRest, Rec>
      : /* stop */ Rec & { [key in Matched]: unknown } & ExtractVariables<Rest>
    : Rec & { [key in Matched]: unknown };

Usage

PostsQuery.groq
*[
 _type == "post"
 && defined(slug) && defined(publishedAt) && hidden != true
 && ($lastPublishedAt == null || publishedAt < $lastPublishedAt)
 && ($category == null || category._ref == $category)
 && ($tag == null || count(tags[_ref == $tag]) > 0)
] {
  publishedAt,
  'slug': slug.current,
} | order(publishedAt desc)[0...$limit]
const PostsQuery = `...`;
/**
 * Equivalent to
 * ```
 * type QueryParams = {
 *   lastPublishedAt: unknown,
 *   category: unknown,
 *   tag: unknown,
 *   limit: unknown,
 *  }
 * ```
 */
type QueryParams = ExtractVariables<typeof PostsQuery>;

TS Play Link