Type Checking

To help identify and prevent errors, front matter and all code blocks are type-checked. This is done using the TypeScript compiler based on the tsconfig.json file local to the project that MDXTS is running in.

Front Matter

Validate front matter fields by passing a generic type to createSource:

data.ts
import { createSource } from 'mdxts'

type FrontMatter = {
  title: string
  date: Date
  summary: string
  tags?: string[]
}

export const allPosts = createSource<{
  frontMatter: FrontMatter
}>('posts/**/*.mdx', { baseDirectory: 'posts' })

This will ensure that all front matter fields are present and have the correct type. For example, the following front matter:

posts/hello-world.mdx
---
title: Hello World
date: 2024-01-01
---

# Hello World

This is my first post.

Results in the following type error:

Error: Front matter data is incorrect or missing
[/posts/hello-world.mdx] Type '{}' does not satisfy the expected type 'frontMatter'.
Type '{}' is missing the following properties from type 'frontMatter': summary

Code Blocks

Allowing errors

If you want to allow errors for a specific code block, you can add an allowErrors prop to the code block meta field:

```tsx allowErrors
const a: string = 1
```
const a: string = 1

This prevents the code block from erroring when the project is type-checked and removes the error indicator and message from the rendered code block.

Allowing specific errors

To allow specific errors, add the allowErrors prop with a comma separated list of error codes:

```tsx allowErrors="2322"
const a: string = 1
```

This is useful for educational purposes when you want to show the error message to the user.

Error numbers can be found in the type error message.

Type Inference

When targeting TypeScript source files, the type checker is used to infer the types of all exports from index.(ts|tsx) files. If package.json exports are defined for the package, they will be used to narrow the set of exports that are analyzed when generating type documentation.

Last updated