Token导航 LogoToken导航TokenDH.com
开发规范需要联网github未标认证来源可访问许可证需确认审计通过

typescript-best-practicesTypeScript 最佳实践

Agent Skill

typescript-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

2,056

周安装

84

GitHub Stars

1

下载量

659
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:typescript-best-practices(TypeScript 最佳实践)
来源仓库:https://github.com/ofershap/typescript-best-practices
仓库路径:skills/typescript-best-practices
安装命令:
npx skills add https://github.com/ofershap/typescript-best-practices --skill typescript-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/ofershap/typescript-best-practices --skill typescript-best-practices

简介

typescript-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理时使用。

  • 适用于 TypeScript 项目协作、代码管理和最佳实践查询等开发规范场景。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装,需结合原始 README 核验具体用法和功能边界。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写操作。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

When to use

Use this skill when working with TypeScript code. AI agents frequently generate outdated patterns - using any instead of unknown, type assertions instead of satisfies, optional fields instead of discriminated unions, and missing strict mode options. This skill enforces modern TypeScript 5.x patterns.

Critical Rules

1. Enable Strict Mode with All Checks

Wrong (agents do this):

{
  "compilerOptions": {
    "strict": false,
    "target": "ES2020"
  }
}

Correct:

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "target": "ES2022"
  }
}

Why: Strict mode catches entire categories of bugs. noUncheckedIndexedAccess prevents unsafe array/object access. Agents often skip these for "convenience."

2. Use satisfies Instead of Type Assertions

Wrong (agents do this):

const config = {
  port: 3000,
  host: "localhost",
} as Config;

config.port.toFixed(); // No error even if port could be string

Correct:

const config = {
  port: 3000,
  host: "localhost",
} satisfies Config;

config.port.toFixed(); // TypeScript knows port is number

Why: satisfies validates the type without widening it. as silences the compiler and can hide bugs. Use satisfies for validation, as only when you genuinely know more than the compiler.

3. Use Discriminated Unions Over Optional Fields

Wrong (agents do this):

interface ApiResponse {
  data?: User;
  error?: string;
  loading?: boolean;
}

Correct:

type ApiResponse =
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; error: string };

Why: Optional fields allow impossible states (data AND error both present). Discriminated unions make each state explicit and exhaustively checkable.

4. Use const Assertions for Literal Types

Wrong (agents do this):

const ROUTES = {
  home: "/",
  about: "/about",
  contact: "/contact",
};
// Type: { home: string; about: string; contact: string }

Correct:

const ROUTES = {
  home: "/",
  about: "/about",
  contact: "/contact",
} as const;
// Type: { readonly home: "/"; readonly about: "/about"; readonly contact: "/contact" }

Why: Without as const, TypeScript widens literal types to string. With it, you get exact literal types and readonly properties.

5. Use unknown Instead of any

Wrong (agents do this):

function parseJson(text: string): any {
  return JSON.parse(text);
}

const data = parseJson('{"name": "test"}');
data.nonExistent.method(); // No error - runtime crash

Correct:

function parseJson(text: string): unknown {
  return JSON.parse(text);
}

const data = parseJson('{"name": "test"}');
if (isUser(data)) {
  data.name; // Safe - type narrowed
}

Why: any disables all type checking. unknown forces you to narrow the type before using it, catching bugs at compile time.

6. Use Template Literal Types for String Patterns

Wrong (agents do this):

function getLocaleMessage(id: string): string { ... }

Correct:

type Locale = 'en' | 'ja' | 'pt';
type MessageKey = 'welcome' | 'goodbye';
type LocaleMessageId = `${Locale}_${MessageKey}`;

function getLocaleMessage(id: LocaleMessageId): string { ... }

Why: Template literal types create precise string patterns from unions. The compiler catches typos and invalid combinations at build time.

7. Use NoInfer to Prevent Unwanted Inference

Wrong (agents do this):

function createLight<C extends string>(colors: C[], defaultColor?: C) { ... }
createLight(['red', 'green', 'blue'], 'purple'); // No error - purple widens C

Correct:

function createLight<C extends string>(colors: C[], defaultColor?: NoInfer<C>) { ... }
createLight(['red', 'green', 'blue'], 'purple'); // Error - 'purple' not in C

Why: NoInfer<T> (TypeScript 5.4+) prevents a parameter from influencing type inference, ensuring stricter checks.

8. Use Branded Types for Type-Safe IDs

Wrong (agents do this):

function getUser(id: string): User { ... }
function getOrder(id: string): Order { ... }

const userId = getUserId();
getOrder(userId); // No error - but wrong!

Correct:

type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };

function getUser(id: UserId): User { ... }
function getOrder(id: OrderId): Order { ... }

const userId = getUserId();
getOrder(userId); // Error - UserId is not OrderId

Why: Branded types prevent accidentally passing one ID type where another is expected. The brand exists only at compile time - zero runtime cost.

9. Use Exhaustive Switch with never

Wrong (agents do this):

function handleStatus(status: "active" | "inactive" | "pending") {
  switch (status) {
    case "active":
      return "Active";
    case "inactive":
      return "Inactive";
    // 'pending' silently falls through
  }
}

Correct:

function handleStatus(status: "active" | "inactive" | "pending") {
  switch (status) {
    case "active":
      return "Active";
    case "inactive":
      return "Inactive";
    case "pending":
      return "Pending";
    default: {
      const _exhaustive: never = status;
      throw new Error(`Unhandled status: ${_exhaustive}`);
    }
  }
}

Why: The never check ensures every union member is handled. When a new status is added, the compiler flags the missing case.

10. Use Type Predicates Over Type Assertions

Wrong (agents do this):

function processItem(item: unknown) {
  const user = item as User;
  console.log(user.name);
}

Correct:

function isUser(item: unknown): item is User {
  return typeof item === "object" && item !== null && "name" in item && "email" in item;
}

function processItem(item: unknown) {
  if (isUser(item)) {
    console.log(item.name); // Safe - narrowed to User
  }
}

Why: Type predicates (item is User) narrow types safely with runtime checks. Type assertions (as User) bypass the compiler and can hide bugs.

11. Use import type for Type-Only Imports

Wrong (agents do this):

import { User, UserService } from "./user";
// User is only used as a type, but gets included in the bundle

Correct:

import type { User } from "./user";
import { UserService } from "./user";

Why: import type is erased at compile time, reducing bundle size. It also makes the intent clear - this import is for types only.

12. Use Record Over Index Signatures

Wrong (agents do this):

interface Config {
  [key: string]: string;
}

Correct:

type Config = Record<string, string>;

// Or better - use a specific union for keys:
type Config = Record<"host" | "port" | "env", string>;

Why: Record<K, V> is more readable and composable than index signatures. When possible, use a union for keys to get exhaustive checking.

13. Use using for Resource Management

Wrong (agents do this):

const file = openFile("data.txt");
try {
  processFile(file);
} finally {
  file.close();
}

Correct:

using file = openFile("data.txt");
processFile(file);
// file.close() called automatically via Symbol.dispose

Why: The using keyword (TypeScript 5.2+) provides deterministic resource cleanup via the Disposable protocol, similar to Python's with or C#'s using.

Patterns

  • Enable strict: true and noUncheckedIndexedAccess: true in every project
  • Use satisfies for type validation without widening
  • Use discriminated unions with a type or kind field for state modeling
  • Use as const for configuration objects and route maps
  • Use branded types for domain-specific IDs
  • Use import type for all type-only imports
  • Use exhaustive switch with never default for union handling

Anti-Patterns

  • NEVER use any - use unknown and narrow with type guards
  • NEVER use as for type assertions unless you genuinely know more than the compiler
  • NEVER use optional fields to model mutually exclusive states - use discriminated unions
  • NEVER use // @ts-ignore or // @ts-expect-error without a comment explaining why
  • NEVER use enum - use as const objects or union types instead
  • NEVER use Function type - use specific function signatures
  • NEVER disable strict mode for convenience

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.88%
按下载量换算236

Claude

32.9%
按下载量换算217

Cursor

19.39%
按下载量换算128

Gemini CLI

9.55%
按下载量换算63

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills