How to Define Custom Types for Content Queries in the Nuxt Content Module

Learn how to define custom types for Nuxt Content queries to streamline your content management. This guide provides a step-by-step approach to define type for your queryContent.

3 min read

November 15th, 2024

Nick Mousavi

Introduction

When using the Nuxt Content module in your Nuxt application, adding TypeScript enhances type-safety and editor autocompletion. This guide explains how to add types to your queries when using the

method to retrieve content.

Query Nuxt Content

Imagine you have defined a front-matter meta-data block at the top of your Markdown content:

/content/my-content.md
---
title: 'Your Title In Here'
date: 2024-11-15
published: true
tags: ['Nuxt', 'Vue']
---

## Introduction
content in here

To retrieve this data in your Vue components:

/pages/index.vue
<script setup>
const { data } = await useAsyncData(() => queryContent('/').findOne())
</script>

<template>
  <pre>
    {{ data }}
  </pre>
</template>

However, you may notice that the

data
object doesn’t include the front-matter meta-data.

Define TypeScript Types

To resolve this, define a TypeScript type for the front-matter meta-data and extend it from

ParsedContent
, which is the default return type for
queryContent
:

/types/content.ts
import type { ParsedContent } from '@nuxt/content'

export interface Content extends ParsedContent {
  title: string
  date: string
  published: boolean
  tags: string[]
}

Now, apply the custom type to the

queryContent
method:

/pages/index.vue
<script setup>
import type { Content } from '/types/content.ts'
const { data } = await useAsyncData(() => queryContent<Content>('/').findOne()) </script>

<template>
  <pre>
    {{ data.date }}
    {{ data.published }}
  </pre>
</template>

This ensures you have access to your custom type in the

data
object.

Tags:NuxtVue