Twoslash
Use Typescript Twoslash in your docs
Usage
Thanks to the Twoslash integration of Shiki, the default code syntax highlighter, it is as simple as adding a transformer.
npm install @hanzo/docs-twoslash twoslashFor Next.js, you need to externalize the following deps:
const config = {
reactStrictMode: true,
serverExternalPackages: ['typescript', 'twoslash'],
};Add to your Shiki transformers.
import { defineConfig } from '@hanzo/docs-mdx/config';
import { transformerTwoslash } from '@hanzo/docs-twoslash';
import { rehypeCodeDefaultOptions } from '@hanzo/docs-core/mdx-plugins';
export default defineConfig({
mdxOptions: {
rehypeCodeOptions: {
themes: {
light: 'github-light',
dark: 'github-dark',
},
transformers: [...(rehypeCodeDefaultOptions.transformers ?? []), transformerTwoslash()],
// important: Shiki doesn't support lazy loading languages for codeblocks in Twoslash popups
// make sure to define them first (e.g. the common ones)
langs: ['js', 'jsx', 'ts', 'tsx'],
},
},
});Add styles, Tailwind CSS v4 is required.
@import '@hanzo/docs-twoslash/twoslash.css';Add MDX components.
import * as Twoslash from '@hanzo/docs-twoslash/ui';
import defaultComponents from '@hanzo/docs-ui/mdx';
import type { MDXComponents } from 'mdx/types';
export function getMDXComponents(components?: MDXComponents) {
return {
...defaultComponents,
...Twoslash,
...components,
} satisfies MDXComponents;
}Now you can add twoslash meta string to codeblocks.
```ts twoslash
console.log('Hello World');
```Cache
Optionally, you can enable filesystem cache with typesCache option:
import { transformerTwoslash } from '@hanzo/docs-twoslash';
import { createFileSystemTypesCache } from '@hanzo/docs-twoslash/cache-fs';
transformerTwoslash({
typesCache: createFileSystemTypesCache(),
});Example
Learn more about Twoslash notations.
type Player = {
/**
* The player name
* @default 'user'
*/
name: string;
};
// ---cut---
// @noErrors
console.g;
// ^|
const player: Player = { name: 'Hello World' };
// ^?const a = '123';
console.log(a);
// ^^^// @errors: 2588
const a = '123';
a = 132;How is this guide?
Last updated on