Fetching preview blog posts from Sanity

type SanitySlug = {
  type: "_slug";
  current: string;
};

type SanityAuthorPreview = {
  name: string;
  image: SanityImageSource;
  slug: SanitySlug;
};

type PreviewPost = {
  title: string;
  slug: SanitySlug;
  mainImage: SanityImageSource;
  publishedAt: string;
  author: SanityAuthorPreview;
};
const previewQuery = groq`
  *[_type == "post" && defined(slug)][]{
    title,
    slug,
    mainImage,
    publishedAt,
    author->{
      name,
      image,
      slug,
    }
  } | order(publishedAt desc)
`;
export async function getPreviewPosts(): Promise<PreviewPost[]> {
  try {
    return await sanityClient.fetch<PreviewPost[]>(previewQuery);
  } catch (err) {
    console.error(err);
    throw new Error("Could not fetch posts preview");
  }
}

Want to download this example?

$ curl https://jezpoz.dev/code-examples/typescript/fetching-preview-blog-posts-from-sanity/raw > example.ts