Skip to content

Installation

The package twoslash is relatively a low-level tool that generating raw type information for the given TypeScript code snippets. This page will focus on low-level programmatic usage. If you are looking for a higher-level tool, check the Syntax Highlighting section.

To install the twoslash package, run the following command:

bash
npm i -D twoslash
bash
pnpm i -D twoslash
bash
yarn add -D twoslash
bash
bun add -D twoslash

Usage

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:

ts
import { 
createTwoslasher
} from 'twoslash'
const
code
= `let a = 'hello'.toUpperCase()`
const
twoslasher
=
createTwoslasher
()
const
result
=
twoslasher
(
code
)

It will output a JavaScript object that contains static type information for each identifier in the code:

ts
{
  "code": "let a = 'hello'.toUpperCase()",
  "nodes": [
    {
      "character": 4,
      "docs": undefined,
      "length": 1,
      "line": 0,
      "start": 4,
      "tags": undefined,
      "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,
      "tags": undefined,
      "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.

Released under the MIT License.