Site Logo

Twoslash 示例

使用 Twoslash 增强 TypeScript 代码显示

TypeScript Twoslash示例

本文档展示了如何在Fumadocs中使用Twoslash功能来提供TypeScript代码高亮和实时类型检查。

基本用法

在代码块中添加 twoslash 元数据字符串即可启用Twoslash功能:

.('Hello World');

类型检查示例

基本类型检查

interface Player {
  : string;
}

const player: Player = { : 'Hello World' };
const player: Player
const = '123'; a = 132; // Error: Cannot assign to 'a' because it is a constant.
Cannot assign to 'a' because it is a constant.

接口定义和使用

interface User {
  : string;
  : string;
  : string;
  ?: number;
}

const : User = {
  : '123',
  : '张三',
  : 'zhangsan@example.com',
};

.(.);

泛型示例

function <>(: ):  {
  return ;
}

const result = <string>('hello');
const result: string

错误提示

interface ApiResponse {
  : boolean;
  : {
    : number;
    : string;
  };
}

const : ApiResponse = {
  : true,
  : {
    : 1,
    : '示例标题',
    extra: '多余属性', // Error: Object literal may only specify known properties
Object literal may only specify known properties, and 'extra' does not exist in type '{ id: number; title: string; }'.
}, };

高级功能

类型推断

type  = { : number; : number };

function (: number, : number):  {
  return { ,  };
}

const point = (10, 20);
const point: Point

联合类型

type  = 'loading' | 'success' | 'error';

function (: ) {
  switch () {
    case 'loading':
      return '加载中...';
    case 'success':
      return '操作成功';
    case 'error':
      return '操作失败';
    default:
      const : never = ;
      return ;
  }
}

工具类型

interface Todo {
  : number;
  : string;
  : boolean;
  : Date;
}

type  = <Todo, 'id' | 'title' | 'completed'>;
type  = <Todo, 'id'>;

const :  = {
  : 1,
  : '学习TypeScript',
  : false,
};

导入和模块

使用导入

// @filename: utils.ts
export function (: Date): string {
  return .();
}

export function (: string): string {
  return .(0).() + .(1);
}

// @filename: main.ts
import { ,  } from './utils';

const  = new ();
const  = ();
const  = ('hello world');

.(, );

使用说明

启用Twoslash

在代码块的开始处添加 twoslash 元数据:

```ts twoslash
// 你的TypeScript代码

### 显示类型信息

使用 `// ^?` 注释来显示变量或表达式的类型:

```ts twoslash
const user = { name: '张三', age: 25 };
//    ^?

错误高亮

Twoslash会自动检测并高亮TypeScript错误:

let count: number = '123'; // Error: Type 'string' is not assignable to type 'number'
Type 'string' is not assignable to type 'number'.

多文件示例

使用 @filename 注释来创建多个文件:

// @filename: types.ts
export interface Person {
  : string;
  : number;
}

// @filename: main.ts
import type { Person } from './types';

const : Person = {
  : '李四',
  : 30,
};

现在你可以在Fumadocs文档中享受完整的TypeScript开发体验,包括智能类型提示、错误检查和代码补全!

这篇指南对你有帮助吗?