TypeScript Coder
专家级 10x 工程师,拥有丰富的 TypeScript 基础知识、迁移策略和最佳实践知识。当要求“添加 TypeScript”、“迁移到 TypeScript”、“添加类型检查”、“创建 TypeScript 配置”、“修复 TypeScript 错误”或使用 .ts/.tsx 文件时使用。支持 JavaScript 到 TypeScript 迁移、JSDoc 类型注释、tsconfig.json 配置和类型安全代码模式。
安装 / 下载方式
TotalClaw CLI推荐
totalclaw install totalclaw:jhauga~typescript-codercURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Ajhauga~typescript-coder/file -o typescript-coder.mdGit 仓库获取源码
git clone https://github.com/openclaw/skills/commit/891b29ace812037359e13482bfee35db640db645## 概述(中文)
专家级 10x 工程师,拥有丰富的 TypeScript 基础知识、迁移策略和最佳实践知识。当要求“添加 TypeScript”、“迁移到 TypeScript”、“添加类型检查”、“创建 TypeScript 配置”、“修复 TypeScript 错误”或使用 .ts/.tsx 文件时使用。支持 JavaScript 到 TypeScript 迁移、JSDoc 类型注释、tsconfig.json 配置和类型安全代码模式。
## 原文
# TypeScript Coder Skill
Master TypeScript development with expert-level knowledge of type systems, migration strategies, and modern JavaScript/TypeScript patterns. This skill transforms you into a 10x engineer capable of writing type-safe, maintainable code and migrating existing JavaScript projects to TypeScript with confidence.
## When to Use This Skill
- User asks to "add TypeScript", "migrate to TypeScript", or "convert to TypeScript"
- Need to "add type checking" or "fix TypeScript errors" in a project
- Creating or configuring `tsconfig.json` for a project
- Working with `.ts`, `.tsx`, `.mts`, or `.d.ts` files
- Adding JSDoc type annotations to JavaScript files
- Debugging type errors or improving type safety
- Setting up TypeScript in a Node.js or JavaScript project
- Creating type definitions or ambient declarations
- Implementing advanced TypeScript patterns (generics, conditional types, mapped types)
## Prerequisites
- Basic understanding of JavaScript (ES6+)
- Node.js and npm/yarn installed (for TypeScript compilation)
- Familiarity with the project structure and build tools
- Access to the `typescript` package (can be installed if needed)
## Shorthand Keywords
Keywords to trigger this skill as if using a command-line tool:
```javascript
openPrompt = ["typescript-coder", "ts-coder"]
```
Use these shorthand commands to quickly invoke TypeScript expertise without lengthy explanations. For example:
- `typescript-coder --check "this code"`
- `typescript-coder check this type guard`
- `ts-coder migrate this file`
- `ts-coder --migrate project-to-typescript`
## Role and Expertise
As a TypeScript expert, you operate with:
- **Deep Type System Knowledge**: Understanding of TypeScript's structural type system, generics, and advanced types
- **Migration Expertise**: Proven strategies for incremental JavaScript to TypeScript migration
- **Best Practices**: Knowledge of TypeScript patterns, conventions, and anti-patterns
- **Tooling Mastery**: Configuration of TypeScript compiler, build tools, and IDE integration
- **Problem Solving**: Ability to resolve complex type errors and design type-safe architectures
## Core TypeScript Concepts
### The TypeScript Type System
TypeScript uses **structural typing** (duck typing) rather than nominal typing:
```typescript
interface Point {
x: number;
y: number;
}
// This works because the object has the right structure
const point: Point = { x: 10, y: 20 };
// This also works - structural compatibility
const point3D = { x: 1, y: 2, z: 3 };
const point2D: Point = point3D; // OK - has x and y
```
### Type Inference
TypeScript infers types when possible, reducing boilerplate:
```typescript
// Type inferred as string
const message = "Hello, TypeScript!";
// Type inferred as number
const count = 42;
// Type inferred as string[]
const names = ["Alice", "Bob", "Charlie"];
// Return type inferred as number
function add(a: number, b: number) {
return a + b; // Returns number
}
```
### Key TypeScript Features
| Feature | Purpose | When to Use |
|---------|---------|-------------|
| **Interfaces** | Define object shapes | Defining data structures, API contracts |
| **Type Aliases** | Create custom types | Union types, complex types, type utilities |
| **Generics** | Type-safe reusable components | Functions/classes that work with multiple types |
| **Enums** | Named constants | Fixed set of related values |
| **Type Guards** | Runtime type checking | Narrowing union types safely |
| **Utility Types** | Transform types | `Partial<T>`, `Pick<T, K>`, `Omit<T, K>`, etc. |
## Step-by-Step Workflows
### Task 1: Install and Configure TypeScript
For a new or existing JavaScript project:
1. **Install TypeScript as a dev dependency**:
```bash
npm install --save-dev typescript
```
2. **Install type definitions for Node.js** (if using Node.js):
```bash
npm install --save-dev @types/node
```
3. **Initialize TypeScript configuration**:
```bash
npx tsc --init
```
4. **Configure `tsconfig.json`** for your project:
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
```
5. **Add build script to `package.json`**:
```json
{
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"check": "tsc --noEmit"
}
}
```
### Task 2: Migrate JavaScript to TypeScript (Incremental Approach)
Safe, incremental migration strategy:
1. **Enable TypeScript to process JavaScript files**:
```json
{
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"noEmit": true
}
}
```
2. **Add JSDoc type annotations to JavaScript files** (optional intermediate step):
```javascript
// @ts-check
/**
* Calculates the sum of two numbers
* @param {number} a - First number
* @param {number} b - Second number
* @returns {number} The sum
*/
function add(a, b) {
return a + b;
}
/** @type {string[]} */
const names = ["Alice", "Bob"];
/** @typedef {{ id: number, name: string, email?: string }} User */
/** @type {User} */
const user = {
id: 1,
name: "Alice"
};
```
3. **Rename files incrementally** from `.js` to `.ts`:
```bash
# Start with utility files and leaf modules
mv src/utils/helpers.js src/utils/helpers.ts
```
4. **Fix TypeScript errors in converted files**:
- Add explicit type annotations where inference fails
- Define interfaces for complex objects
- Handle `any` types appropriately
- Add type guards for runtime checks
5. **Gradually convert remaining files**:
- Start with utilities and shared modules
- Move to leaf components (no dependencies)
- Finally convert orchestration/entry files
6. **Enable strict mode progressively**:
```json
{
"compilerOptions": {
"strict": false,
"noImplicitAny": true,
"strictNullChecks": true
// Enable other strict flags one at a time
}
}
```
### Task 3: Define Types and Interfaces
Creating robust type definitions:
1. **Define interfaces for data structures**:
```typescript
// User data model
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
readonly createdAt: Date; // Read-only property
}
// API response structure
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
};
}
```
2. **Use type aliases for complex types**:
```typescript
// Union type
type Status = 'pending' | 'active' | 'completed' | 'failed';
// Intersection type
type Employee = User & {
employeeId: string;
department: string;
salary: number;
};
// Function type
type TransformFn<T, U> = (input: T) => U;
// Conditional type
type NonNullable<T> = T extends null | undefined ? never : T;
```
3. **Create type definitions in `.d.ts` files** for external modules:
```typescript
// types/custom-module.d.ts
declare module 'custom-module' {
export interface Config {
apiKey: string;
timeout?: number;
}
export function initialize(config: Config): Promise<void>;
export function fetchData<T>(endpoint: string): Promise<T>;
}
```