返回 Skill 列表
extension
分类: 开发与工程无需 API Key

devs:typescript-core

全面的TypeScript开发指南,涵盖配置、类型安全、架构模式和最佳实践。在处理TypeScript代码库时使用,包括(1)TypeScript配置与设置(tsconfig.json、严格模式),(2)类型定义与模式(工具类型、类型安全方法),(3)解决TypeScript编译错误,(4)应用TypeScript最佳实践(项目结构、错误处理、包选择)。当在.ts/.tsx文件中工作或解决特定于TypeScript的问题时自动触发。

person作者: jakexiaohubgithub

TypeScript Core

Comprehensive guidance for TypeScript development with strict type safety, functional patterns, and modern tooling.

Core Principles

Follow these fundamental principles in all TypeScript work:

  1. TypeScript Only (Strict Mode) - Always enable strict mode and all type-checking flags
  2. Simplicity First (KISS + YAGNI) - Do the simplest thing that works, avoid speculative architecture
  3. Type Safety - Use Result/Effect types instead of throwing exceptions
  4. Functional Patterns - Prefer composition, immutability, and pure functions
  5. User Experience First - Clear error messages, predictable behavior

See principles.md for detailed guidance.

Quick Start

Setting Up a New TypeScript Project

  1. Choose the appropriate tsconfig template based on project type:

  2. Install required dependencies - Always use the latest versions with pnpm:

    pnpm add -D typescript @types/node
    pnpm add effect zod true-myth @logtape/logtape
    
  3. Configure strict linting - See strict-configuration.md for ESLint and Prettier setup

  4. Organize project structure - Follow feature-oriented layout from project-structure.md

Resolving TypeScript Errors

When encountering TypeScript compilation errors:

  1. Read the full error message - Includes file, line, and often helpful suggestions
  2. Check common-errors.md - Quick solutions for frequent errors
  3. Verify strict mode configuration - Ensure all flags from strict-configuration.md are enabled
  4. Use type utilities - See type-utilities.md for built-in helpers

TypeScript Configuration

All projects must use strict TypeScript configuration to catch errors early and maintain code quality.

Key requirements:

  • Enable strict: true (includes all strict type-checking options)
  • Enable noUncheckedIndexedAccess: true (not in strict by default, prevents undefined array access issues)
  • Use latest TypeScript version
  • Zero compiler errors or warnings before commit

See strict-configuration.md for complete tsconfig.json and ESLint setup.

Type Safety & Patterns

Handling Nullable Values

Prefer True Myth's Maybe type over null/undefined:

import Maybe from 'true-myth/maybe';

// Instead of: User | null
function findUser(id: string): Maybe<User> {
  const user = db.findById(id);
  return Maybe.of(user);
}

// Use with chaining
const userName = findUser("123")
  .map(user => user.name)
  .unwrapOr("Unknown");

Handling Errors

Use Result types instead of throwing exceptions:

import Result from 'true-myth/result';

// Instead of throwing
function parseConfig(data: string): Result<Config, ParseError> {
  try {
    const parsed = JSON.parse(data);
    return Result.ok(parsed);
  } catch (e) {
    return Result.err(new ParseError("Invalid JSON", e));
  }
}

// Use with pattern matching
parseConfig(data)
  .match({
    Ok: config => console.log("Config loaded:", config),
    Err: error => console.error("Parse failed:", error)
  });

For complex async operations, prefer Effect over raw Promises - See error-handling.md for complete strategy.

TypeScript Utility Types

Leverage built-in utility types for type transformations:

  • Partial<T> - Make all properties optional (partial updates)
  • Required<T> - Make all properties required
  • Pick<T, K> - Extract specific properties (DTOs, API responses)
  • Omit<T, K> - Exclude properties (hide sensitive fields)
  • Record<K, V> - Type-safe dictionaries/maps
  • ReturnType<T> - Extract function return type
  • Parameters<T> - Extract function parameter types

See type-utilities.md for comprehensive guide with examples.

Coding Patterns

Composition Over Inheritance

Favor composing functionality rather than class hierarchies:

// Prefer this
const withLogging = <T extends (...args: any[]) => any>(fn: T) => {
  return ((...args: Parameters<T>) => {
    logger.info("Calling function", { args });
    return fn(...args);
  }) as T;
};

// Over this
class LoggableService extends BaseService {
  // ...
}

Railway-Oriented Error Flow

Chain operations with Effect or Result types to handle errors gracefully:

import { pipe } from 'effect';
import Result from 'true-myth/result';

const result = pipe(
  validateInput(data),
  Result.andThen(processData),
  Result.andThen(saveToDatabase),
  Result.mapErr(err => new ApplicationError("Process failed", err))
);

See patterns.md for complete pattern library including immutability, pattern matching, and concurrency patterns.

Project Organization

Structure projects by feature, not by technical type:

src/
├── features/
│   └── users/
│       ├── components/
│       ├── services/
│       ├── hooks/
│       └── types.ts
├── lib/
│   ├── api/
│   └── utils/
└── state/

See project-structure.md for complete layouts for web apps, backends, CLIs, and monorepos.

Package Ecosystem

Always Use (Standard Toolkit)

These packages are included by default in new projects:

  • Effect - Functional effect system for async/concurrent operations
  • Zod - Schema validation at boundaries (API inputs, env vars)
  • True Myth - Maybe/Result types for null safety and error handling
  • LogTape - Structured logging with redaction and integrations
  • Oclif - CLI framework (for CLI projects)

See packages-always-use.md for detailed rationale and usage.

Utility Libraries

Context-specific packages for common needs:

CLI Tools

For command-line applications:

  • Ink (rich TUI), Inquirer (prompts), Ora (spinners), cli-progress
  • See packages-cli.md

Testing

Use Vitest with Testing Library for all tests:

import { describe, it, expect } from 'vitest';

describe('UserService', () => {
  it('should create user with valid input', () => {
    const result = createUser({ name: "Alice", email: "alice@example.com" });
    expect(result.isOk()).toBe(true);
  });
});

See testing.md for complete testing strategy including React component testing, Effect testing, and MSW for API mocking.

Code Review Standards

Before submitting code:

  1. Zero errors - tsc --noEmit passes with no errors
  2. Zero warnings - ESLint and Prettier checks pass
  3. Tests pass - All tests green
  4. Follows patterns - Uses Result/Maybe, Effect for async, proper error handling
  5. Proper naming - See naming.md for conventions

See code-review.md for complete checklist.

Dependency Management

  • Always use latest versions - Update dependencies regularly
  • Use pnpm - Required package manager for all projects
  • Audit security - Run pnpm audit before releases
  • Lock file committed - pnpm-lock.yaml always in version control

See dependencies.md for update strategies and security practices.

Reference Files

Configuration & Setup:

Patterns & Practices:

TypeScript-Specific:

Packages:

Templates

Pre-configured tsconfig.json files for quick project setup: