### Vue Single File Component Example
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/vue.md
Demonstrates a basic Vue Single File Component with script setup, reactive state, and lifecycle hooks.
```vue
```
--------------------------------
### Install twoslash-eslint with bun
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/eslint.md
Install the twoslash-eslint package as a development dependency using bun.
```bash
bun add -D twoslash-eslint
```
--------------------------------
### Install Twoslash
Source: https://context7.com/twoslashes/twoslash/llms.txt
Install Twoslash as a development dependency using npm, pnpm, or yarn.
```bash
npm i -D twoslash
# or
pnpm i -D twoslash
# or
yarn add -D twoslash
```
--------------------------------
### Install twoslash-vue with bun
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/vue.md
Install the twoslash-vue package as a development dependency using bun.
```bash
bun add -D twoslash-vue
```
--------------------------------
### Install twoslash-eslint with pnpm
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/eslint.md
Install the twoslash-eslint package as a development dependency using pnpm.
```bash
pnpm i -D twoslash-eslint
```
--------------------------------
### Install twoslash with bun
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/install.md
Use this command to install twoslash as a development dependency using bun.
```bash
bun add -D twoslash
```
--------------------------------
### Vue Component Setup with Context and Event Handling
Source: https://github.com/twoslashes/twoslash/blob/main/packages/twoslash-vue/test/results/renderer/example.raw.html
This snippet demonstrates a Vue component's setup, including context access, event handling for a button click, and rendering messages and counts. It utilizes internal Vue types and macros.
```typescript
type __VLS_SetupExposed = import('vue').type ShallowUnwrapRef = T extends ShallowReactiveBrandClass ? T : { [K in keyof T]: DistributeRef; }
export ShallowUnwrapRefShallowUnwrapRef<{
count: Refcount: typeof const count: Refcount;
}>;
const __VLS_ctx = {
...{} as type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : anyObtain the return type of a constructor function typeInstanceType<__VLS_PickNotAny {}>>,
...{} as __VLS_SetupExposed,
};
type __VLS_LocalComponents = __VLS_SetupExposed;
type __VLS_GlobalComponents = import('vue').GlobalComponents;
let __VLS_components!: __VLS_LocalComponents & __VLS_GlobalComponents;
let __VLS_intrinsics!: import('vue/jsx-runtime').JSX.interface JSX.IntrinsicElementsIntrinsicElements;
type __VLS_LocalDirectives = __VLS_SetupExposed;
let __VLS_directives!: __VLS_LocalDirectives & import('vue').GlobalDirectives;
__VLS_asFunctionalElement1(__VLS_intrinsics.button: ButtonHTMLAttributes & ReservedPropsbutton, __VLS_intrinsics.button: ButtonHTMLAttributes & ReservedPropsbutton)({
...{ onClick?: ((payload: PointerEvent) => void) | undefinedonClick: (...[$event: PointerEvent$event]) => {
__VLS_ctx.count: numbercount++;
// @ts-ignore
[const count: Refcount,];
}},
});
( __VLS_ctx.msg: stringmsg );
( __VLS_ctx.count: numbercount );
type __VLS_RootEl =
| __VLS_Elements['button'];
// @ts-ignore
[const count: Refcount,msg,];
return (await import('vue')).function defineComponent, string, {}, {}, string, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, {}, string, {}, {}, {}, string, ComponentProvideOptions, {}, {}, {}, any>(options: {
props?: string[] | (ComponentObjectPropsOptions & ThisType) | undefined;
__typeProps?: unknown;
__typeEmits?: {} | undefined;
__typeRefs?: {} | undefined;
__typeEl?: any;
} & ComponentOptionsBase, ... 15 more ..., ComponentProvideOptions> & ThisType<...>): DefineComponent<...> (+2 overloads)defineComponent({
});
})();
```
--------------------------------
### Install twoslash with pnpm
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/install.md
Use this command to install twoslash as a development dependency using pnpm.
```bash
pnpm i -D twoslash
```
--------------------------------
### Install twoslash-eslint with yarn
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/eslint.md
Install the twoslash-eslint package as a development dependency using yarn.
```bash
yarn add -D twoslash-eslint
```
--------------------------------
### Install twoslash-vue with npm
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/vue.md
Install the twoslash-vue package as a development dependency using npm.
```bash
npm i -D twoslash-vue
```
--------------------------------
### Install twoslash-eslint with npm
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/eslint.md
Install the twoslash-eslint package as a development dependency using npm.
```bash
npm i -D twoslash-eslint
```
--------------------------------
### Install twoslash-vue with pnpm
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/vue.md
Install the twoslash-vue package as a development dependency using pnpm.
```bash
pnpm i -D twoslash-vue
```
--------------------------------
### Install twoslash with yarn
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/install.md
Use this command to install twoslash as a development dependency using yarn.
```bash
yarn add -D twoslash
```
--------------------------------
### Install twoslash-vue with yarn
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/vue.md
Install the twoslash-vue package as a development dependency using yarn.
```bash
yarn add -D twoslash-vue
```
--------------------------------
### Install Twoslash CDN via npm
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/cdn.md
Install the twoslash-cdn package as a development dependency for local bundling.
```bash
npm i -D twoslash-cdn
```
--------------------------------
### defineSlots
Source: https://github.com/twoslashes/twoslash/blob/main/packages/twoslash-vue/test/results/renderer/example.raw.html
Provides type hints for IDEs for slot names and slot props type checking within `
{{ msg }}
`
const twoslasher = createTwoslasher()
const result = twoslasher(code, 'vue')
```
--------------------------------
### Declare and Initialize Tuple Type (TypeScript)
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/index.md
Demonstrates the correct and incorrect initialization of a TypeScript tuple type. This example shows how Twoslash can be used to highlight type errors.
```typescript
// Declare a tuple type
let x: [string, number]
// Initialize it
x = ['hello', 10]
// Initialize it incorrectly
x = [10, 'hello']
```
--------------------------------
### Provide Default Values for Props with Type-based defineProps
Source: https://github.com/twoslashes/twoslash/blob/main/packages/twoslash-vue/test/results/renderer/example.raw.html
Use `withDefaults` inside `
```
--------------------------------
### Basic ESLint Check Example
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/eslint.md
Demonstrates a simple TypeScript code snippet that ESLint can check for unused variables and type definitions.
```typescript
const unused = 1
type Foo = {
bar: string
}
```
--------------------------------
### Define Component Slots with defineSlots
Source: https://github.com/twoslashes/twoslash/blob/main/packages/twoslash-vue/test/results/renderer/example.raw.html
Use defineSlots to provide type hints for slot names and props, enhancing IDE support for slot usage within
```
--------------------------------
### twoslasher
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/api.md
A shorthand function for directly getting results from code. It creates a new TypeScript language server on each call, making `createTwoslasher` the preferred option for performance.
```APIDOC
## `twoslasher`
The `twoslasher` function is a shorthand for directly getting the result from the code. It will create a new TypeScript language server every time it is called. Ideally, `createTwoslasher` should be preferred.
```ts
import { twoslasher } from 'twoslash'
const code = `console.log("Hello World")`
const result = twoslasher(code, 'ts', { /* options */ })
```
```
--------------------------------
### Configure Twoslash Instance with CreateTwoslashOptions
Source: https://context7.com/twoslashes/twoslash/llms.txt
Use `createTwoslasher` with `CreateTwoslashOptions` for custom TypeScript instances, virtual file systems, caching, and node filtering. Provide a custom TypeScript module, set the virtual file system root, or add extra ambient files.
```typescript
import { createTwoslasher } from 'twoslash'
import ts from 'typescript'
const twoslasher = createTwoslasher({
// Provide a custom TypeScript module (useful in monorepos)
tsModule: ts,
// Root directory for the virtual FS overlay
vfsRoot: process.cwd(),
// Extra ambient files pre-loaded into all runs
extraFiles: {
'globals.d.ts': 'declare const __VERSION__: string',
},
// Filter hover nodes by identifier name
shouldGetHoverInfo: (identifier, _start, _filename) => {
return !identifier.startsWith('_')
},
// Filter any node from the output
filterNode: node => node.type !== 'highlight',
// Custom tag names to extract (e.g., // @log)
customTags: ['log', 'warn'],
// Bring your own cache map (e.g., to share across instances)
cache: new Map(),
// Disable FS read caching (default: true)
fsCache: true,
})
const result = twoslasher('const x: __VERSION__ = "1.0"', 'ts')
```
--------------------------------
### Display compiled output with `@showEmit`
Source: https://context7.com/twoslashes/twoslash/llms.txt
Use `// @showEmit` to replace the code sample with its TypeScript-emitted JavaScript, or `// @showEmittedFile: filename.ext` to specify which emitted file (e.g., `.d.ts`) to display.
```ts
import { twoslasher } from 'twoslash'
// Show the emitted .js
const r1 = twoslasher(
`
// @showEmit
const level: string = 'Danger'
`,
'ts'
)
console.log(r1.code)
// => '"use strict";\nconst level = \'Danger\';\n'
console.log(r1.meta.extension) // => "js"
// Show the emitted .d.ts declaration file
const r2 = twoslasher(
`
// @declaration
// @showEmit
// @showEmittedFile: index.d.ts
export const hello = 'world'
`,
'ts'
)
console.log(r2.code)
// => 'export declare const hello = "world";\n'
```
--------------------------------
### Create Twoslash ESLint Runner
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/eslint.md
Initialize the Twoslash ESLint runner with custom ESLint configurations. Provide your ESLint FlatConfig array to the `eslintConfig` option.
```typescript
import { createTwoslasher } from 'twoslash-eslint'
const code = `
console.log('Code to lint')
`
const twoslasher = createTwoslasher({
// Provide the ESLint FlatConfig array here
eslintConfig: [
{
files: ['**'],
plugins: { /* ... */ },
rules: { /* ... */ }
}
]
})
const result = twoslasher(code, 'index.ts')
```
--------------------------------
### Show Emitted .d.ts.map File in Twoslash
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `@showEmittedFile: index.d.ts.map` with `@declarationMap` and `@showEmit` to display the declaration map file, primarily for project references.
```ts
// @declaration
// @declarationMap
// @showEmit
// @showEmittedFile: index.d.ts.map
export const hello: string = 'world'
```
--------------------------------
### Create and reuse Twoslash language servers
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/api.md
Use `createTwoslasher` to cache language servers for repetitive usages. This significantly improves performance by reusing initialized files and language servers.
```typescript
import { createTwoslasher } from 'twoslash'
const twoslasher = createTwoslasher({
// ...your custom options.
})
const result1 = twoslasher('import { ref } from "vue"', 'ts')
// The second time will be much faster as the types from `vue` is already.
const result2 = twoslasher('import { computed } from "vue"', 'ts')
```
--------------------------------
### `CreateTwoslashOptions` — Advanced instance configuration
Source: https://context7.com/twoslashes/twoslash/llms.txt
Configure the `createTwoslasher` function with custom TypeScript instances, virtual file systems, caching, and node filtering for advanced usage.
```APIDOC
## `CreateTwoslashOptions` — Advanced instance configuration
Options for `createTwoslasher` (and `twoslasher`) covering custom TypeScript instances, virtual file systems, caching, and node filtering.
```ts
import { createTwoslasher } from 'twoslash'
import ts from 'typescript'
const twoslasher = createTwoslasher({
// Provide a custom TypeScript module (useful in monorepos)
tsModule: ts,
// Root directory for the virtual FS overlay
vfsRoot: process.cwd(),
// Extra ambient files pre-loaded into all runs
extraFiles: {
'globals.d.ts': 'declare const __VERSION__: string',
},
// Filter hover nodes by identifier name
shouldGetHoverInfo: (identifier, _start, _filename) => {
return !identifier.startsWith('_')
},
// Filter any node from the output
filterNode: node => node.type !== 'highlight',
// Custom tag names to extract (e.g., // @log)
customTags: ['log', 'warn'],
// Bring your own cache map (e.g., to share across instances)
cache: new Map(),
// Disable FS read caching (default: true)
fsCache: true,
})
const result = twoslasher('const x: __VERSION__ = "1.0"', 'ts')
```
```
--------------------------------
### Show Emitted .d.ts File in Twoslash
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `@showEmittedFile: index.d.ts` with `@declaration` and `@showEmit` to display the declaration file.
```ts
// @declaration
// @showEmit
// @showEmittedFile: index.d.ts
export const hello = 'world'
```
--------------------------------
### Configure Twoslash behavior with `HandbookOptions`
Source: https://context7.com/twoslashes/twoslash/llms.txt
Control Twoslash's behavior via `handbookOptions`, set either inline with `// @option` or programmatically. Options include error handling, hover info collection, and emitted file display.
```ts
import { createTwoslasher } from 'twoslash'
const twoslasher = createTwoslasher({
handbookOptions: {
errors: [], // expected TS error codes
noErrors: false, // suppress all/specific errors
noErrorValidation: false,// skip error guard throwing
noStaticSemanticInfo: false, // skip hover info collection
showEmit: false, // replace output with emitted JS
showEmittedFile: undefined, // which emitted file to show
keepNotations: false, // keep notation comments in output
noErrorsCutted: false, // ignore errors in cut regions
},
})
// Example: disable hover collection for performance
const twoslasher2 = createTwoslasher({
handbookOptions: { noStaticSemanticInfo: true },
})
const result = twoslasher2('const x = 42', 'ts')
console.log(result.hovers) // => []
```
--------------------------------
### Completion Query with `^|` Notation
Source: https://context7.com/twoslashes/twoslash/llms.txt
Use the `^|` notation below a partial expression to trigger auto-complete suggestions at that position. The result includes the completion prefix and a list of suggested completions.
```typescript
import { twoslasher } from 'twoslash'
const result = twoslasher(`
// @noErrors
console.e
// ^|
`, 'ts')
const completion = result.completions[0]
console.log(completion.completionsPrefix) // => "e"
console.log(completion.completions.map(c => c.name))
// => ["error", "exception", ...]
```
--------------------------------
### Twoslash CDN with IndexedDB Cache Persistence
Source: https://github.com/twoslashes/twoslash/blob/main/docs/packages/cdn.md
Configure Twoslash CDN to use IndexedDB for persistent caching of fetched files using unstorage.
```html
```
--------------------------------
### Show Emitted .js.map File in Twoslash
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `@showEmittedFile: index.js.map` with `@sourceMap` and `@showEmit` to display the JavaScript source map file.
```ts
// @sourceMap
// @showEmit
// @showEmittedFile: index.js.map
export const hello = 'world'
```
--------------------------------
### createTwoslasher
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/api.md
Creates a cached language server instance for faster repetitive operations. It initializes a TypeScript language server and caches it for reuse, significantly improving performance for multiple calls.
```APIDOC
## `createTwoslasher`
Twoslash runs a TypeScript language server to get the information, which could be a heavy operation to load and parse all the files it needs. In repetitive usages, you may not want to initialize the language server every simple time. Twoslash provides a `createTwoslasher` factory function allows you to cache the language servers and reuse the already initialized files.
```ts
import { createTwoslasher } from 'twoslash'
const twoslasher = createTwoslasher({
// ...your custom options.
})
const result1 = twoslasher('import { ref } from "vue"', 'ts')
// The second time will be much faster as the types from `vue` is already.
const result2 = twoslasher('import { computed } from "vue"', 'ts')
```
This would result in a 5-20 times faster performance in repetitive usage.
To avoid getting interference across runs, it will reuse the language server with the same `compilerOptions`. Internally it holds a map of hashed `compilerOptions` to the language server instances.
You can retrieve the cached map and clear it when necessary, to avoid memory leaks:
```ts
import { createTwoslasher } from 'twoslash'
const twoslasher = createTwoslasher()
// Do something...
// Clear the cached language servers, free the memory.
twoslasher.getCacheMap()?.clear()
```
```
--------------------------------
### Define Vue Component with Options API
Source: https://github.com/twoslashes/twoslash/blob/main/packages/twoslash-vue/test/results/renderer/example.raw.html
Defines a Vue component named 'HelloWorld' using the Options API, including props, data, and methods. The `greet` method logs the `msg` prop to the console.
```typescript
import { function ref(value: T): [T] extends [Ref] ? IfAny, T> : Ref, UnwrapRef | T> (+1 overload)Takes an inner value and returns a reactive and mutable ref object, which
has a single property `.value` that points to the inner value.@paramvalue - The object to wrap in the ref.@see{@link https://vuejs.org/api/reactivity-core.html#ref}ref, const computed: {
(getter: ComputedGetter, debugOptions?: DebuggerOptions): ComputedRef;
(options: WritableComputedOptions, debugOptions?: DebuggerOptions): WritableComputedRef;
}computed } from 'vue'
export default {} as typeof __VLS_export;
const __VLS_self = (await import('vue')).function defineComponent, string, {}, {}, string, {
msg: string;
}, {}, {}, {
greet(): void;
}, ComponentOptionsMixin, ComponentOptionsMixin, {}, string, {}, {}, {}, string, ComponentProvideOptions, {}, {}, {}, any>(options: {
props?: string[] | (ComponentObjectPropsOptions & ThisType) | undefined;
__typeProps?: unknown;
__typeEmits?: {} | undefined;
__typeRefs?: {} | undefined;
__typeEl?: any;
} & ComponentOptionsBase, ... 15 more ..., ComponentProvideOptions> & ThisType<...>): DefineComponent<...> (+2 overloads)defineComponent({
ComponentOptionsBase = {}, Directives extends Record = {}, Exposed extends string = string, Provide extends ComponentProvideOptions = ComponentProvideOptions>.name?: string | undefinedname: 'HelloWorld',
LegacyOptions, { msg: string; }, {}, { greet(): void; }, ComponentOptionsMixin, ComponentOptionsMixin, {}, string, ComponentProvideOptions>.data?: ((this: CreateComponentPublicInstanceWithMixins<...>, vm: CreateComponentPublicInstanceWithMixins, {}, {}, {}, MethodOptions, ComponentOptionsMixin, ComponentOptionsMixin, {}, ToResolvedProps<{}, {}>, {}, false, {}, {}, {}, {}, string, {}, any, ComponentProvideOptions, OptionTypesType<{}, {}, {}, {}, {}, {}>, Readonly<{}> & Readonly<{}>, {}, {}, {}, MethodOptions, {}>) => {
...;
}) | undefineddata() {
return {
msg: stringmsg: 'Hello!'
}
},
LegacyOptions, { msg: string; }, {}, { greet(): void; }, ComponentOptionsMixin, ComponentOptionsMixin, {}, string, ComponentProvideOptions>.methods?: {
greet(): void;
} | undefinedmethods: {
function greet(): voidgreet() {
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(this.msg: stringmsg)
}
}
});
```
--------------------------------
### Highlight code ranges with `^^^`
Source: https://context7.com/twoslashes/twoslash/llms.txt
Use `^^^` below a line to create a `NodeHighlight` for renderers to style. The `hl.start` and `hl.length` properties provide the position and size of the highlighted range.
```ts
import { twoslasher } from 'twoslash'
const result = twoslasher(
`
function add(a: number, b: number) {
// ^^^
return a + b
}
`,
'ts'
)
const hl = result.highlights[0]
console.log(hl.start) // position of 'add' in output code
console.log(hl.length) // 3
```
--------------------------------
### Show Emitted .js File for Specific Module in Twoslash
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `@showEmittedFile: b.js` with `@showEmit` to display the emitted JavaScript file for a specific module (`b.ts`) in a multi-file sample.
```ts
// @showEmit
// @showEmittedFile: b.js
// @filename: a.ts
export const helloWorld: string = 'Hi'
// @filename: b.ts
import { helloWorld } from './a'
console.log(helloWorld)
```
--------------------------------
### Cut code sections with `// ---cut---` notations
Source: https://context7.com/twoslashes/twoslash/llms.txt
Use `// ---cut---`, `// ---cut-before---`, `// ---cut-after---`, or `// ---cut-start---` with `// ---cut-end---` to remove boilerplate code while maintaining program context and position mapping.
```ts
import { twoslasher } from 'twoslash'
// Only show code after the cut line
const r1 = twoslasher(
`
const level: string = 'Danger'
// ---cut---
console.log(level)
`,
'ts'
)
console.log(r1.code) // => "console.log(level)\n"
// Cut a range in the middle
const r2 = twoslasher(
`
const level: string = 'Danger'
// ---cut-start---
console.log(level) // hidden
// ---cut-end---
console.log('shown')
`,
'ts'
)
console.log(r2.code)
// => "const level: string = 'Danger'\nconsole.log('shown')\n"
// Multi-file: hide the setup file, show only the consumer
const r3 = twoslasher(
`
// @filename: a.ts
export const helloWorld: string = 'Hi'
// ---cut---
// @filename: b.ts
import { helloWorld } from './a'
console.log(helloWorld)
`,
'ts'
)
console.log(r3.code)
// => "// @filename: b.ts\nimport { helloWorld } from './a'\nconsole.log(helloWorld)\n"
```
--------------------------------
### Cut Code Before with ---cut---
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `// ---cut---` or `// ---cut-before---` to remove code from the output that appears before this marker. This is useful for simplifying samples by removing irrelevant boilerplate.
```typescript
const level: string = 'Danger'
// ---cut---
console.log(level)
```
```typescript
// @filename: a.ts
export const helloWorld: string = 'Hi'
// ---cut---
// @filename: b.ts
import { helloWorld } from './a'
console.log(helloWorld)
```
--------------------------------
### Render TypeScript Code with Twoslash and Shiki
Source: https://github.com/twoslashes/twoslash/blob/main/packages/twoslash-cdn/examples/index.html
Prepares TypeScript source code for type checking and then renders it to HTML using Shiki with the Twoslash transformer. This process ensures that type information is available for accurate syntax highlighting.
```typescript
const app = document.getElementById('app')
const source = `
import { ref } from '@vue/reactivity'
console.log("Hi! Shiki + Twoslash on CDN :)")
const count = ref(0)
// ^?
`.trim()
// Before rendering, we need to prepare the types, so that the rendering could happend synchronously
await twoslash.prepareTypes(source)
// Then we can render the code
app.innerHTML = await codeToHtml(source, {
lang: 'ts',
theme: 'vitesse-dark',
transformers: [transformerTwoslash],
})
```
--------------------------------
### Define multiple files with `// @filename:`
Source: https://context7.com/twoslashes/twoslash/llms.txt
Separate a Twoslash code block into multiple virtual files using `// @filename:`. Only `// @filename:` notations are retained in the output unless removed by cutting.
```ts
import { twoslasher } from 'twoslash'
const result = twoslasher(
`
// @filename: types.ts
export interface User { name: string; age: number }
// @filename: index.ts
import type { User } from './types'
const user: User = { name: 'Alice', age: 30 }
// ^?
`,
'ts'
)
console.log(result.queries[0].text)
// => "const user: User"
```
--------------------------------
### Shiki Integration for Syntax Highlighting with Twoslash
Source: https://context7.com/twoslashes/twoslash/llms.txt
Integrates Twoslash with Shiki for syntax highlighting, rendering compiler-accurate, annotated code blocks in HTML. This transformer injects Twoslash type popups into the highlighted code.
```ts
import { transformerTwoslash } from '@shikijs/twoslash'
import { codeToHtml } from 'shiki'
const html = await codeToHtml(
`const msg = 'hello'\n// ^?`,
{
lang: 'ts',
theme: 'vitesse-dark',
transformers: [
transformerTwoslash(), // injects Twoslash type popups
],
}
)
// For VitePress: use @shikijs/vitepress-twoslash
// vitepress config:
import { transformerTwoslash as vpTwoslash } from '@shikijs/vitepress-twoslash'
export default defineConfig({
markdown: {
codeTransformers: [vpTwoslash()],
},
})
```
--------------------------------
### `twoslasherLegacy` / `convertLegacyReturn` — `@typescript/twoslash` compatibility
Source: https://context7.com/twoslashes/twoslash/llms.txt
Provides a compatibility layer for migrating from `@typescript/twoslash`, returning the old result shape with `staticQuickInfos`, `queries`, `renderedMessage`, etc.
```APIDOC
## `twoslasherLegacy` / `convertLegacyReturn` — `@typescript/twoslash` compatibility
Compatibility layer for migrating from `@typescript/twoslash`. Returns the old result shape with `staticQuickInfos`, `queries` (with `kind`), `renderedMessage`, etc.
```ts
import { convertLegacyReturn, twoslasher, twoslasherLegacy } from 'twoslash'
// Option 1: drop-in replacement
const legacyResult = twoslasherLegacy('import { ref } from "vue"', 'ts')
console.log(legacyResult.staticQuickInfos[0].text) // old interface
// Option 2: convert new result to legacy shape manually
const newResult = twoslasher('const x = 42', 'ts')
const legacy = convertLegacyReturn(newResult)
console.log(legacy.staticQuickInfos)
console.log(legacy.errors[0]?.renderedMessage)
console.log(legacy.playgroundURL) // always "" (removed from new API)
```
```
--------------------------------
### Generate Playground URL
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/migrate.md
If the `playgroundURL` is needed, it can be manually calculated by compressing the code using `lz-string` and constructing the URL. This is an alternative to the removed feature in the new twoslash implementation.
```typescript
declare const code: string
// ---
import lzString from 'lz-string'
const zipped = lzString.compressToEncodedURIComponent(code)
const playgroundURL = `https://www.typescriptlang.org/play/#code/${zipped}`
```
--------------------------------
### Cut Code Between with ---cut-start--- and ---cut-end---
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `// ---cut-start---` and `// ---cut-end---` pair to exclude a specific section of code from the output. Multiple pairs can be used, but they must be balanced.
```typescript
const level: string = 'Danger'
// ---cut-start---
console.log(level) // This is not shown.
// ---cut-end---
console.log('This is shown')
```
--------------------------------
### Integrate Twoslash Transformer with Shiki
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/highlight.md
Use the `transformerTwoslash` from `@shikijs/twoslash` to enable Twoslash integration within Shiki's `codeToHtml` function. This requires importing both the transformer and `codeToHtml`.
```ts
import { transformerTwoslash } from '@shikijs/twoslash' // [!code hl]
import { codeToHtml } from 'shiki'
const html = await codeToHtml(`console.log()`, {
lang: 'ts',
theme: 'vitesse-dark',
transformers: [
transformerTwoslash(), // [!code hl]
],
})
```
--------------------------------
### `twoslash-eslint` — ESLint rule visualization
Source: https://context7.com/twoslashes/twoslash/llms.txt
Runs ESLint on code and returns lint messages as `NodeError` nodes in the Twoslash format, enabling inline rendering of ESLint diagnostics in documentation code blocks.
```APIDOC
## `twoslash-eslint` — ESLint rule visualization
Runs ESLint on code and returns lint messages as `NodeError` nodes in the Twoslash format. Enables rendering ESLint diagnostics inline in documentation code blocks, just like TypeScript errors.
```ts
import antfu from '@antfu/eslint-config'
import { createTwoslasher } from 'twoslash-eslint'
const twoslasher = createTwoslasher({
eslintConfig: await antfu(),
includeDocs: true, // append rule doc URL to error message
mergeMessages: true, // merge overlapping range messages
})
const result = twoslasher(`
const x = 1;
var y = 2
`, 'ts')
result.nodes.forEach(n => {
if (n.type === 'error')
console.log(`[${n.level}] ${n.text} at ${n.line}:${n.character}`)
})
// => [warning] ... (style/no-var) at 2:0
```
```
--------------------------------
### Compose Legacy Return Conversion
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/migrate.md
Manually compose the legacy return format by using `twoslasher` with the new interface and then converting the result using `convertLegacyReturn`. This approach provides more control over the migration process.
```typescript
import { convertLegacyReturn, twoslasher } from 'twoslash'
const result = twoslasher('import { ref } from "vue"', 'ts') // new interface
const legacy = convertLegacyReturn(result) // <--
console.log(legacy.staticQuickInfos) // the old interface
```
--------------------------------
### Display Emitted JavaScript with @showEmit
Source: https://github.com/twoslashes/twoslash/blob/main/docs/refs/notations.md
Use `// @showEmit` to replace the TypeScript code sample with its compiled JavaScript output. This demonstrates how TypeScript transforms the code, including type stripping and adding directives like 'use strict'.
```typescript
// @showEmit
const level: string = 'Danger'
```
--------------------------------
### Vue SFC Support with twoslash-vue
Source: https://context7.com/twoslashes/twoslash/llms.txt
The `twoslash-vue` package extends Twoslash with Vue Single File Component support using `@vue/language-core`. It handles `.vue` files transparently, mapping positions between Vue source and generated TypeScript. Custom Vue compiler options can be provided.
```typescript
import { createTwoslasher } from 'twoslash-vue'
const twoslasher = createTwoslasher()
const result = twoslasher(`
`, 'vue')
console.log(result.queries[0].text)
// => "const count: Ref"
// With Vue compiler options
const twoslasher2 = createTwoslasher({
vueCompilerOptions: { target: 3.3 },
debugShowGeneratedCode: false, // set true to see generated TS
})
```
--------------------------------
### Create a Twoslash instance
Source: https://github.com/twoslashes/twoslash/blob/main/docs/guide/install.md
Import and call `createTwoslasher` to initialize a Twoslash instance, which caches the TypeScript language service for performance. This instance can then be used to process code snippets.
```typescript
import { createTwoslasher } from 'twoslash'
const code = `let a = 'hello'.toUpperCase()`
const twoslasher = createTwoslasher()
const result = twoslasher(code)
```