How to show TypeScript type annotations in code snippets
- 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.
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
interfacePerson {name : string}interfacePerson {age : number}// `Person` is now merged and expects `name` and `age`constProperty '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'.: p 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
consta = {joo : 'test'};Property 'foo' does not exist on type '{ joo: string; }'.2339Property 'foo' does not exist on type '{ joo: string; }'.console .log (a .); foo
And then, you can use some fancy markdown syntax to inspect variables and even show possible auto-completion values.
js
consta = {test : 'test'testTwo : 'test'testThree : 'test'};console .log (a .te console .log (a );
Wild! 🤯
I'm not entirely convinced I'll use Twoslash for every code snippet on the blog, but for TypeScript snippets — heck yeah!
Join 5.4k readers and learn something new every week with Web Weekly.