Want to take your Astro code highlights to the next level? This guide will show you how to add TypeScript snippets with hover-over type information, making your code examples more interactive and informative.
Start with an Astro project. Follow the official Astro quickstart guide to set up your project.
Astro includes Shiki for syntax highlighting. Here’s how to optimize it for TypeScript snippets:
- Update your
astro.config.mjs:
import { defineConfig } from "astro/config";
export default defineConfig({
markdown: {
shikiConfig: {
themes: { light: "min-light", dark: "tokyo-night" },
wrap: true,
},
},
});
- Add a stylish border to your code blocks:
pre:has(code) {
@apply border border-skin-line;
}
To add type information to your code blocks, you can use TypeScript’s built-in type annotations:
// @errors: 2322
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Doe",
age: "30", // Type error: Type 'string' is not assignable to type 'number'
};
console.log(user.name);
You can also show type information inline:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Doe",
age: 30,
};
// The type of user.name is 'string'
const name = user.name;
Your Astro site now includes:
- Advanced syntax highlighting
- Type information in code blocks
- Adaptive light and dark mode code blocks
These features enhance code readability and user experience, making your code examples more valuable to readers.