mcpField
T
typescript

typescript

github.com/gentleman-programming开发661496 次安装31 周前更新
代码仓库

关于 typescript

面向 TypeScript 开发的编码规范技能,汇总类型定义、接口设计和类型安全等实践,供编写或审查代码时参考。

主要功能

  1. 01常量对象推导联合类型
  2. 02保持接口扁平
  3. 03避免使用 any
  4. 04运用工具类型与泛型
  5. 05使用类型守卫和类型导入

适用场景

  1. 01定义状态等字面量类型
  2. 02设计用户等数据结构
  3. 03解析并验证未知输入

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/gentleman-programming/gentleman-skills --skill typescript

安装后在 Claude Code 中输入/typescript确认已加载。

详细介绍

常量类型模式(必需)

// ✅ ALWAYS: Create const object first, then extract type
const STATUS = {
  ACTIVE: "active",
  INACTIVE: "inactive",
  PENDING: "pending",
} as const;

type Status = (typeof STATUS)[keyof typeof STATUS];

// ❌ NEVER: Direct union types
type Status = "active" | "inactive" | "pending";

为什么? 单一事实来源、运行时值、自动补全、更易重构。

扁平接口(必需)

// ✅ ALWAYS: One level depth, nested objects → dedicated interface
interface UserAddress {
  street: string;
  city: string;
}

interface User {
  id: string;
  name: string;
  address: UserAddress;  // Reference, not inline
}

interface Admin extends User {
  permissions: string[];
}

// ❌ NEVER: Inline nested objects
interface User {
  address: { street: string; city: string };  // NO!
}

永远不要使用 any

// ✅ Use unknown for truly unknown types
function parse(input: unknown): User {
  if (isUser(input)) return input;
  throw new Error("Invalid input");
}

// ✅ Use generics for flexible types
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

// ❌ NEVER
function parse(input: any): any { }

工具类型

Pick<User, "id" | "name">     // Select fields
Omit<User, "id">              // Exclude fields
Partial<User>                 // All optional
Required<User>                // All required
Readonly<User>                // All readonly
Record<string, User>          // Object type
Extract<Union, "a" | "b">     // Extract from union
Exclude<Union, "a">           // Exclude from union
NonNullable<T | null>         // Remove null/undefined
ReturnType<typeof fn>         // Function return type
Parameters<typeof fn>         // Function params tuple

类型守卫

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

导入类型

import type { User } from "./types";
import { createUser, type Config } from "./utils";

关键词

typescript、ts、类型、接口、泛型、严格模式、工具类型

评论

支持 Markdown