TypeScript Twoslash

A markup format for TypeScript code, ideal for creating self-contained code samples which let the TypeScript compiler do the extra leg-work.

If you know TypeScript, you basically know twoslash.

Twoslash adds the ability to declare tsconfig options inline, split a sample into multiple files and a few other useful commands. You can see the full API inside the README

The Twoslash markup language helps with:

  • Enforcing accurate errors from a TypeScript code sample, and leaving the messaging to the compiler
  • Splitting a code sample to hide distracting code
  • Declaratively highlighting symbols in your code sample
  • Replacing code with the results of transpilation to different files, or ancillary files like .d.ts or .map files
  • Handle multi-file imports in a single code sample
  • Creating a playground link for the code

Markup

See how TS Twoslash will grab the highlight information for identifiers in your code

// @errors: 2532

declareconst quantumString: string | undefined;

// Right now this string is in two states, hover below to see

quantumString

if (quantumString) {

// However, in here we now have a different type

// you can verify by hovering below

quantumString.length;
}

Enter to Rename, Shift+Enter to Preview

Highlights runtime types

Show Errors

Set Compiler Flags

Trims code

Show the JS

Show the DTS

Highlights

Results

Exception Raised

Errors were thrown in the sample, but not included in an errors tag

These errors were not marked as being expected: 2339. The existing annotation specified 2532

Compiler Errors:

index.tsx [2339] 255 - Property 'length' does not exist on type 'string'.

Usage

Twoslash's usage guide is available on the npm README at @typescript/twoslash.