Command Palette

Search for a command to run...

Назад к скиллам
скилл № 29041

frontend-typescript-patterns

Use when the user asks about TypeScript in frontend code: generic components, discriminated unions for UI state, type guards and narrowing, type-safe API…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить frontend-typescript-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

TypeScript Patterns for Frontend

Purpose

Write type-safe frontend code with generic components, typed API clients, discriminated unions for state, and reliable type guards.

Agent Protocol

Trigger

Exact user phrases: "TypeScript patterns", "generic components", "type-safe API", "discriminated unions", "type guards", "type narrowing", "TS patterns", "type-safe React".

Input Context

Before activating, verify:

  • The frontend framework in use (React, Vue, Angular, etc.).
  • Whether the focus is on components, API clients, or state types.

Output Artifact

No file output. Produces TypeScript pattern implementations as text.

Response Format

Pattern: {name}
File: {file path suggestion}
Code:
{code block with TS implementation}

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

  • Generic components use proper constraint bounds (extends) — never any.
  • API client returns typed responses with discriminated success/error union.
  • UI state modeled as discriminated union — no boolean flags for mutually exclusive states.
  • Type guards narrow correctly at runtime.
  • No unsafe casts (as) without a type guard or zod schema backing them.

Max Response Length

4096 tokens.

TypeScript Architecture / Decision Trees

Pattern Selection Decision Tree

What type of code are you writing?
  |-- Component that renders different data types -->
  |     GENERIC COMPONENT with <T extends ...>
  |     Usage: List<T>, Table<T>, Select<T>
  |     Constraint: extends to limit allowed types
  |
  |-- API call that returns unknown shape -->
  |     TYPE-SAFE API CLIENT with Zod schema parsing
  |     Never: raw `as` cast
  |     Return: discriminated union { status, data | error }
  |
  |-- State that has multiple mutually-exclusive shapes -->
  |     DISCRIMINATED UNION with `status` discriminator
  |     Never: multiple boolean flags (isLoading, isError, isSuccess)
  |     Pattern: AsyncState<T> = idle | loading | success | error
  |
  |-- Runtime type check for a union type -->
  |     TYPE GUARD function: `is X` using `value is Type`
  |     Pattern: function isAdmin(user): user is Admin
  |
  |-- Variant mapping with safe access -->
        CONSTRAINED PROPS with Record<K, V> using exhaustive key check
        Pattern: Record<ButtonVariant, string>

Type Safety Decision Tree

Can the value's shape change at runtime?
  |-- NO (statically known) -->
  |     Plain TypeScript interface or type is sufficient
  |     No runtime validation needed
  |
  |-- YES (API response, user input, localStorage) -->
  |     |-- Can use Zod schema? -->
  |     |     YES: Zod.parse() at the boundary, infer type from schema
  |     |     NO: Write a type guard function with runtime checks
  |     |
  |     |-- Never cast with `as` unless you validated first
  |
  |-- It's a framework boundary (props, events) -->
        Use satisfies to constrain to a type while keeping literal values

Workflow

Step 1: Generic Components

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

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

// Usage — type inferred from data
<List
  items={users}
  renderItem={(u) => u.name}
  keyExtractor={(u) => u.id}
/>

Step 2: Type-Safe API Client

type ApiResponse<T> =
  | { status: 'success'; data: T }
  | { status: 'error'; code: number; message: string }

async function apiGet<T>(
  url: string,
  schema: z.ZodSchema<T>
): Promise<ApiResponse<T>> {
  try {
    const res = await fetch(url)
    if (!res.ok) {
      return { status: 'error', code: res.status, message: res.statusText }
    }
    const json = await res.json()
    const parsed = schema.parse(json)
    return { status: 'success', data: parsed }
  } catch (err) {
    return { status: 'error', code: 0, message: (err as Error).message }
  }
}

// Usage
const res = await apiGet('/api/users', userArraySchema)
if (res.status === 'success') {
  // res.data is typed as User[]
}

Step 3: Discriminated Unions for State

// Instead of boolean flags:
type AsyncState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string }

function useAsync<T>(fn: () => Promise<T>): AsyncState<T> {
  const [state, setState] = useState<AsyncState<T>>({ status: 'idle' })
  // ...
  return state
}

// Usage — exhaustive switch
switch (state.status) {
  case 'loading': return <Spinner />
  case 'error':   return <Error msg={state.error} />
  case 'success': return <Data data={state.data} />
  case 'idle':    return <Initial />
}

Step 4: Type Guards


Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/ts-generics-patterns.md
  • references/ts-react-patterns.md
  • references/ts-type-safety.md
  • references/ts-utility-types.md
  • references/typescript-advanced.md
  • references/typescript-config.md

FAQ

Что делает скилл frontend-typescript-patterns?

Use when the user asks about TypeScript in frontend code: generic components, discriminated unions for UI state, type guards and narrowing, type-safe API clients, satisfies, typing props and events. Produces type-safe component and API patterns. Not for TypeScript language basics or compiler setup (use typescript).

Как установить скилл frontend-typescript-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл frontend-typescript-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить frontend-typescript-patterns с