TypeScript Snippets in Astro: Show, Don't Tell

Alexander Opalic - Sep 22 - - Dev Community

Note: Since I use Shiki and Twoslash I recommend you check out the blog post on the original site to get the full experience. TypeScript Snippets in Astro: Show, Don't Tell

Want smarter code snippets on your Astro site? This guide shows you how to add TypeScript type info that appears on hover. No fluff, just the steps you need. Your readers will thank you.

Before You Start

Set up an Astro project. Need help? See the Astro quickstart guide.

Set Up Shiki for Syntax Highlighting

Astro includes Shiki. Let's configure it:

  1. Edit astro.config.mjs:
import { defineConfig } from "astro/config";

export default defineConfig({
  markdown: {
    shikiConfig: {
      themes: { light: "min-light", dark: "tokyo-night" },
    },
  },
});
Enter fullscreen mode Exit fullscreen mode
  1. Add a border to code blocks in your CSS:
pre:has(code) {
  @apply border border-skin-line;
}
Enter fullscreen mode Exit fullscreen mode

Add Twoslash for Type Information

  1. Install packages:
npm i -D twoslash twoslash-vue
Enter fullscreen mode Exit fullscreen mode
  1. Update astro.config.mjs:
import { createTransformerFactory, rendererRich } from '@shikijs/twoslash/core'
import { createTwoslasher } from 'twoslash-vue'
import { defineConfig } from "astro/config";

export default defineConfig({
  markdown: {
    shikiConfig: {
      themes: { light: "min-light", dark: "tokyo-night" },
      transformers: [
        createTransformerFactory(createTwoslasher())({
          langs: ['ts', 'tsx', 'vue'],
          renderer: rendererRich({
            lang: 'ts',
          }),
        }),
      ],
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Use Interactive Snippets

Create TypeScript snippets in Markdown:

code snippet Markdown

The // ^? shows where type info appears on hover.

Vue snippets work too:

Image description

For autocompletion, use ^|:

const increment = () => {
  count.v
  //    ^|
}
Enter fullscreen mode Exit fullscreen mode

What You've Gained

Your Astro site now has:

  • Syntax highlighting
  • Hover-over type info
  • Light/dark mode code blocks

Your readers will thank you.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player