Installation
The package twoslash is relatively a low-level tool that generating raw type information for the given TypeScript code snippets. This page will force on low-level programtic usages. If you are looking for a higher-level tool, check the integrations section.
To install the twoslash package, run the following command:
npm i -D twoslashpnpm i -D twoslashyarn add -D twoslashbun add -D twoslashUsage
To use it, you can call the createTwoSlasher function to create a TwoSlash instance where it will cache the TypeScript language service internally for better performance:
import { createTwoSlasher } from 'twoslash'
const code = `let a = 'hello'.toUpperCase()`
const twoslasher = createTwoSlasher()
const result = twoslasher(code)It will outputs a JavaScript object that contains static type information for each identifier in the code:
{
"code": "let a = 'hello'.toUpperCase()",
"nodes": [
{
"character": 4,
"docs": undefined,
"length": 1,
"line": 0,
"start": 4,
"target": "a",
"text": "let a: string",
"type": "hover",
},
{
"character": 16,
"docs": "Converts all the alphabetic characters in a string to uppercase.",
"length": 11,
"line": 0,
"start": 16,
"target": "toUpperCase",
"text": "(method) String.toUpperCase(): string",
"type": "hover",
},
],
}With this, you can render the code snippets how you want. Or, you can check the Syntax Highlighting section to see how you use it along with a tool like Shiki to get beautiful syntax highlighting.