13
Typescript hints in your code samples
Adding code samples to your website is an excellent idea. It shows how the code should look like. It's hard to image npm package docs without code samples.
Existing solutions are good when we want to show JavaScript code samples. But what, when we want to show TypeScript code, types alongside with code?
… Shiki Twoslash is the library you are looking for.
You can display typescript hints in two types.
Static:
const msg = "Hi world" as const;
// ^?
Dynamic:
ts twoslash
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property];
};
type LockedAccount = {
readonly id: string;
readonly name: string;
};
type UnlockedAccount = CreateMutable<LockedAccount>;
Note: You need to attach JavaScript code to have interactive code hints.
Shiki Twoslash supports more functionalities:
- mixing static with dynamic mode
- showing typescript errors
- vs code themes
Also, we come with plugins for the most popular tools: Eleventy, Docusaurus, Gatsby, and more.
You can read more about all options on shiki twoslash website.
To get in touch with me you can find me on Twitter.
13