Token导航 LogoToken导航

Agent Skill · 前端设计

typescript-patterns(TypeScript 模式)

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

typescript-patterns 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在前端设计类的 10,216 个 Skill 里排第 6,232。

总安装 539周安装 22GitHub Stars 公开资料未说明下载 172核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/code-visionary/react-router-skills --skill typescript-patterns

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

用于辅助 React、Next.js 等前端项目的 TypeScript 开发。提供类型安全的 loader、action 和组件编写模式。帮助构建可维护的前端代码,提升开发体验。涉及页面改动时应配合本地预览确认视觉效果。安装方式:github,通过 npx skills add 命令添加指定仓库技能。

来源仓库内路径:skills/typescript-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/code-visionary/react-router-skills --skill typ…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

typescript-patterns 怎么安装?

在终端执行 npx skills add https://github.com/code-visionary/react-router-skills --skill typescript-pa…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

typescript-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

typescript-patterns 需要什么权限?

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

typescript-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

typescript-patterns 用的人多吗?

公开数据是累计安装 539 次,近一周安装 22 次,下载 172 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

typescript-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
frontend-design

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
typescript-patterns

TypeScript 模式 · 本页

539—需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

TypeScript Patterns

Master TypeScript in React and React Router v7 applications. Learn how to create type-safe loaders, actions, components, and leverage TypeScript's power for better DX.

Quick Reference

Type-Safe Loader

export async function loader({ params }: LoaderFunctionArgs) {
  const user = await fetchUser(params.userId);
  return { user };
}

// In component
const { user } = useLoaderData<typeof loader>();

Type-Safe Action

export async function action({ request }: ActionFunctionArgs) {
  const data = await request.formData();
  return { success: true };
}

// In component
const actionData = useActionData<typeof action>();

Generic Component

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
}

function List<T>({ items, renderItem }: ListProps<T>) {
  return <ul>{items.map(renderItem)}</ul>;
}

When to Use This Skill

  • Setting up TypeScript in React Router project
  • Creating type-safe routes
  • Building reusable generic components
  • Defining API response types
  • Improving IDE autocomplete and error detection
  • Refactoring JavaScript to TypeScript

Core TypeScript for React Router

1. Loader Types

import type { LoaderFunctionArgs } from "react-router";

// Define return type interface
interface LoaderData {
  user: User;
  posts: Post[];
}

export async function loader({
  params,
  request
}: LoaderFunctionArgs): Promise<LoaderData> {
  const user = await fetchUser(params.userId);
  const posts = await fetchPosts(params.userId);

  return { user, posts };
}

// Type-safe component
export default function Profile() {
  const { user, posts } = useLoaderData<typeof loader>();
  //    ^? { user: User; posts: Post[] }

  return (
    <div>
      <h1>{user.name}</h1>
      {posts.map(post => (
        <div key={post.id}>{post.title}</div>
      ))}
    </div>
  );
}

2. Action Types

import type { ActionFunctionArgs } from "react-router";

// Define action response types
type ActionSuccess = {
  success: true;
  user: User;
};

type ActionError = {
  success: false;
  errors: Record<string, string[]>;
};

type ActionData = ActionSuccess | ActionError;

export async function action({
  request
}: ActionFunctionArgs): Promise<ActionData> {
  const formData = await request.formData();

  // Validation...
  if (hasErrors) {
    return {
      success: false,
      errors: { email: ["Invalid email"] }
    };
  }

  const user = await createUser(formData);
  return { success: true, user };
}

// Type-safe component
export default function CreateUser() {
  const actionData = useActionData<typeof action>();

  if (actionData?.success === false) {
    // TypeScript knows this is ActionError
    return <div>{actionData.errors.email}</div>;
  }

  if (actionData?.success === true) {
    // TypeScript knows this is ActionSuccess
    return <div>Created {actionData.user.name}</div>;
  }

  return <Form method="post">{/* ... */}</Form>;
}

3. Params Typing

import type { LoaderFunctionArgs, Params } from "react-router";

// Define expected params
interface RouteParams extends Params {
  userId: string;
  postId: string;
}

export async function loader({ params }: LoaderFunctionArgs) {
  // Type assertion for strict checking
  const { userId, postId } = params as RouteParams;

  return { userId, postId };
}

// Alternative: Runtime validation + type safety
import { z } from "zod";

const paramsSchema = z.object({
  userId: z.string(),
  postId: z.string(),
});

export async function loader({ params }: LoaderFunctionArgs) {
  const { userId, postId } = paramsSchema.parse(params);
  //    ^? { userId: string; postId: string }

  return { userId, postId };
}

4. Zod Integration

import { z } from "zod";

// Define schema
const createUserSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().positive(),
});

// Infer TypeScript type from schema
type CreateUserInput = z.infer<typeof createUserSchema>;
//   ^? { name: string; email: string; age: number }

export async function action({ request }: ActionFunctionArgs) {
  const formData = await request.formData();

  const result = createUserSchema.safeParse({
    name: formData.get("name"),
    email: formData.get("email"),
    age: Number(formData.get("age")),
  });

  if (!result.success) {
    return {
      errors: result.error.flatten().fieldErrors,
    };
  }

  // result.data is fully typed as CreateUserInput
  const user = await createUser(result.data);

  return { user };
}

React Component Patterns

1. Props Interface

// Define props clearly
interface ButtonProps {
  children: React.ReactNode;
  onClick: () => void;
  variant?: "primary" | "secondary";
  disabled?: boolean;
}

export function Button({
  children,
  onClick,
  variant = "primary",
  disabled = false
}: ButtonProps) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`btn-${variant}`}
    >
      {children}
    </button>
  );
}

2. Generic Components

// Generic list component
interface ListProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  keyExtractor: (item: T) => string | number;
}

export function List<T>({
  items,
  renderItem,
  keyExtractor
}: ListProps<T>) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={keyExtractor(item)}>
          {renderItem(item, index)}
        </li>
      ))}
    </ul>
  );
}

// Usage with type inference
<List
  items={users}  // users: User[]
  renderItem={(user) => <span>{user.name}</span>}
  //          ^? user: User (inferred!)
  keyExtractor={(user) => user.id}
/>

3. Event Handlers

interface FormProps {
  onSubmit: (data: FormData) => void;
}

export function Form({ onSubmit }: FormProps) {
  // Properly typed event handler
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    onSubmit(formData);
  };

  // Properly typed input handler
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />
    </form>
  );
}

4. Forwarding Refs

import { forwardRef } from "react";

interface InputProps {
  label: string;
  error?: string;
}

// Properly typed ref forwarding
export const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ label, error }, ref) => {
    return (
      <div>
        <label>{label}</label>
        <input ref={ref} />
        {error && <span>{error}</span>}
      </div>
    );
  }
);

Input.displayName = "Input";

5. Children Patterns

// Accept any valid React children
interface ContainerProps {
  children: React.ReactNode;
}

// Accept only specific component types
interface TabsProps {
  children: React.ReactElement<TabProps> | React.ReactElement<TabProps>[];
}

// Accept render prop
interface DataProviderProps<T> {
  data: T;
  children: (data: T) => React.ReactNode;
}

export function DataProvider<T>({ data, children }: DataProviderProps<T>) {
  return <>{children(data)}</>;
}

Advanced Patterns

1. Discriminated Unions

// Define mutually exclusive states
type LoadingState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; error: string };

function UserProfile() {
  const [state, setState] = useState<LoadingState>({
    status: "idle"
  });

  // TypeScript narrows type based on status
  switch (state.status) {
    case "idle":
      return <div>Click to load</div>;

    case "loading":
      return <div>Loading...</div>;

    case "success":
      // TypeScript knows state.data exists here
      return <div>{state.data.name}</div>;

    case "error":
      // TypeScript knows state.error exists here
      return <div>Error: {state.error}</div>;
  }
}

2. Type Guards

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

// Usage
const data: unknown = await response.json();

if (isUser(data)) {
  // TypeScript knows data is User here
  console.log(data.name);
}

3. Utility Types

// Pick specific properties
type UserPreview = Pick<User, "id" | "name" | "avatar">;

// Omit properties
type UserWithoutPassword = Omit<User, "password">;

// Make all properties optional
type PartialUser = Partial<User>;

// Make all properties required
type RequiredUser = Required<User>;

// Make all properties readonly
type ReadonlyUser = Readonly<User>;

// Extract keys of certain type
type StringKeys<T> = {
  [K in keyof T]: T[K] extends string ? K : never;
}[keyof T];

type UserStringFields = StringKeys<User>;
//   ^? "name" | "email" | "bio"

4. Mapped Types

// Create form state from model
type FormState<T> = {
  [K in keyof T]: {
    value: T[K];
    error?: string;
    touched: boolean;
  };
};

type UserFormState = FormState<User>;
// {
//   name: { value: string; error?: string; touched: boolean }
//   email: { value: string; error?: string; touched: boolean }
//   ...
// }

5. Conditional Types

// Different return type based on input
type LoaderReturn<T extends boolean> =
  T extends true
    ? Promise<Response>
    : Response;

function createLoader<T extends boolean>(
  async: T
): LoaderReturn<T> {
  // Implementation
  return null as any;
}

const syncLoader = createLoader(false);
//    ^? Response

const asyncLoader = createLoader(true);
//    ^? Promise<Response>

API Response Typing

1. Domain Model Pattern

// API response type (snake_case)
interface UserAPI {
  user_id: string;
  full_name: string;
  email_address: string;
  created_at: string;
}

// Domain model (camelCase)
interface User {
  id: string;
  name: string;
  email: string;
  createdAt: Date;
}

// Transformation functions
export const User = {
  fromAPI(data: UserAPI): User {
    return {
      id: data.user_id,
      name: data.full_name,
      email: data.email_address,
      createdAt: new Date(data.created_at),
    };
  },

  toAPI(user: User): UserAPI {
    return {
      user_id: user.id,
      full_name: user.name,
      email_address: user.email,
      created_at: user.createdAt.toISOString(),
    };
  },
};

// Usage in loader
export async function loader() {
  const response = await fetch("/api/users");
  const data: UserAPI = await response.json();
  const user = User.fromAPI(data);

  return { user };
}

2. Generic API Client

// Generic fetch function with type safety
async function apiCall<T>(
  url: string,
  options?: RequestInit
): Promise<T> {
  const response = await fetch(url, options);

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}

// Usage
const user = await apiCall<User>("/api/users/123");
//    ^? User

const posts = await apiCall<Post[]>("/api/posts");
//    ^? Post[]

Common Issues

Issue 1: Type 'any' Errors

Symptoms: TypeScript complains about implicit any Cause: Missing type annotations Solution: Add explicit types

// ❌ Implicit any
function processData(data) {
  return data.map(item => item.value);
}

// ✅ Explicit types
function processData(data: DataItem[]): number[] {
  return data.map(item => item.value);
}

Issue 2: Type Assertion Overuse

Symptoms: Many as casts in code Cause: Fighting TypeScript instead of fixing types Solution: Define proper types

// ❌ Too many assertions
const user = data as User;
const name = user.name as string;

// ✅ Proper typing
interface ApiResponse {
  data: User;
}

const response: ApiResponse = await fetch(...);
const user = response.data;
const name = user.name;

Issue 3: Overly Complex Types

Symptoms: Unreadable type definitions Cause: Trying to be too clever Solution: Simplify and document

// ❌ Too complex
type ComplexType<T, U extends keyof T> = {
  [K in U]: T[K] extends object ? Readonly<T[K]> : T[K]
};

// ✅ Simpler and clearer
type UserFields = Pick<User, "name" | "email">;

Best Practices

  • Enable strict mode in tsconfig.json
  • Use typeof loader for type inference
  • Define interfaces for all props
  • Use Zod for runtime validation + type inference
  • Create domain models with fromAPI/toAPI
  • Use discriminated unions for states
  • Avoid any - use unknown instead
  • Prefer interfaces over type aliases for objects
  • Use generic components for reusability
  • Document complex types with comments

Anti-Patterns

Things to avoid:

  • ❌ Using any everywhere
  • ❌ Type assertions without validation (as User)
  • ❌ Disabling TypeScript errors with @ts-ignore
  • ❌ Not typing function parameters
  • ❌ Overly complex generic types
  • ❌ Duplicating types instead of reusing
  • ❌ Not using discriminated unions for state
  • ❌ Mixing runtime and type-only imports

tsconfig.json Setup

{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "Bundler",

    // Strict type checking
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,

    // React
    "jsx": "react-jsx",
    "jsxImportSource": "react",

    // Module resolution
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,

    // Output
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

References

平台分布

Codex

35.79%
按下载量换算62

Claude

30.25%
按下载量换算52

Cursor

18.12%
按下载量换算31

Gemini CLI

8.09%
按下载量换算14

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

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

继续浏览同类 Skills