Published at
Updated at
Reading time
1min

Sometimes, I blog about TypeScript, and I always wondered if it's possible to render type annotations in syntax-highlighted code snippets on this blog.

Previous Google searches didn't help me, so here's another contribution to the internet: I finally found a project that allows rendering type annotations in code snippets.

Say hello to "Shiki Twoslash"

Twoslash allows you to add TypeScript type information to your code snippets. In their words, Twoslash is:

markdown code samples powered by the syntax engine of Visual Studio Code mixed with the TypeScript compiler’s information.

And that's pretty incredible, because it's also able to validate your code and show possible Typescript errors.

ts
interface Person {
name: string
}
 
interface Person {
age: number
}
 
// `Person` is now merged and expects `name` and `age`
const p: Person = {
Property 'name' is missing in type '{ age: number; }' but required in type 'Person'.2741Property 'name' is missing in type '{ age: number; }' but required in type 'Person'.
age: 99
}

You can let Twoslash do its job; if your snippets aren't correct, it'll complain and error out (unless you tell it that you expect an error like above).

And because it uses the VS Code type checker, it works for JavaScript snippets, too!

js
const a = {
joo: 'test'
};
 
console.log(a.foo);
Property 'foo' does not exist on type '{ joo: string; }'.2339Property 'foo' does not exist on type '{ joo: string; }'.

And then, you can use some fancy markdown syntax to inspect variables and even show possible auto-completion values.

js
const a = {
test: 'test'
testTwo: 'test'
testThree: 'test'
};
 
console.log(a.te
                
 
 
console.log(a);
const a: { test: string; testTwo: string; testThree: string; }

Wild! 🤯

I'm not entirely convinced I'll use Twoslash for every code snippet on the blog, but for TypeScript snippets — heck yeah!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles