Логотип Typescript Patterns

Typescript Patterns

Спільнота
kazdenc
typescript-patterns

TypeScript best practices and advanced type design patterns. Use when writing, reviewing, or refactoring TypeScript code. Covers type narrowing, generics, utility types, discriminated unions, error handling, and module patterns. Triggers on TypeScript, type safety, or type design tasks.

Огляд

Видавецьkazdenc
Репозиторійbuilder-skills
Назва навичкиtypescript-patterns
Зірки
46
Форки
5
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем kazdenc. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Typescript Patterns у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/kazdenc/builder-skills/tree/main/.claude/skills/dev/frameworks/typescript-patterns
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/kazdenc/builder-skills.git /tmp/builder-skills
mkdir -p .claude/skills
cp -r /tmp/builder-skills/.claude/skills/dev/frameworks/typescript-patterns .claude/skills/typescript-patterns
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Typescript Patterns в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Typescript Patterns, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Typescript Patterns не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

TypeScript Patterns

Apply these patterns when writing, reviewing, or refactoring TypeScript code. Prefer type safety over convenience. Catch errors at compile time, not runtime.

Type Design Principles

Default to the narrowest type that accurately represents the data. Widen only when you have a concrete reason.

PrincipleDoDon't
Narrow typesstatus: "active" | "inactive"status: string
Branded types for IDstype UserId = string & { __brand: "UserId" }userId: string (mixable with any string)
Discriminated unions{ kind: "circle"; radius: number } | { kind: "rect"; w: number; h: number }Type assertions to distinguish shapes
Readonly by defaultreadonly items: Item[]Mutable arrays unless mutation is required
Explicit return types on public APIsfunction getUser(id: UserId): Promise<User>Inferred return types on exported functions

Branded Types

Use branded types to prevent accidental mixing of structurally identical values:

typescript
type UserId = string & { readonly __brand: unique symbol };
type OrderId = string & { readonly __brand: unique symbol };

function createUserId(id: string): UserId {
  return id as UserId;
}

function getOrder(orderId: OrderId): Order { /* ... */ }

// Compile error: UserId is not assignable to OrderId
getOrder(createUserId("abc"));

Generics

Use generics when a function or type operates on a value whose type the caller determines. Don't add generics speculatively — add them when you have two or more concrete use cases.

Constraining Generics

Always constrain generics to the narrowest interface they need:

typescript
// Good — constrained to what the function actually uses
function getProperty<T extends Record<string, unknown>, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Bad — unconstrained, anything goes
function getProperty<T>(obj: T, key: string): unknown { /* ... */ }

Common Generic Patterns

Factory pattern — return typed instances:

typescript
function createRepository<T extends { id: string }>(collection: string) {
  return {
    findById(id: string): Promise<T | null> { /* ... */ },
    save(entity: T): Promise<void> { /* ... */ },
    delete(id: string): Promise<void> { /* ... */ },
  };
}

const users = createRepository<User>("users");

Builder pattern — chain methods with progressive type narrowing:

typescript
class QueryBuilder<T> {
  where<K extends keyof T>(field: K, value: T[K]): this { /* ... */ }
  select<K extends keyof T>(...fields: K[]): QueryBuilder<Pick<T, K>> { /* ... */ }
  build(): Query<T> { /* ... */ }
}

Inference helper — let TypeScript infer from arguments:

typescript
function createAction<TInput, TOutput>(config: {
  input: z.ZodSchema<TInput>;
  handler: (input: TInput) => Promise<TOutput>;
}) { /* ... */ }

// TInput and TOutput are inferred from usage
createAction({
  input: z.object({ name: z.string() }),
  handler: async (input) => ({ id: "1", name: input.name }),
});

Utility Types

Use built-in utility types instead of hand-rolling equivalents. Here is when to reach for each:

Utility TypeUse WhenExample
Pick<T, K>You need a subset of propertiesPick<User, "id" | "name"> for a summary view
Omit<T, K>You need everything except certain propertiesOmit<User, "password"> for a public response
Partial<T>All properties become optional (patch/update payloads)Partial<User> for an update endpoint
Required<T>All properties become requiredRequired<Config> after merging with defaults
Record<K, V>You need a typed dictionaryRecord<StatusCode, string> for a lookup table
Extract<T, U>Pull members of a union that match a conditionExtract<Event, { kind: "click" }>
Exclude<T, U>Remove members of a union that match a conditionExclude<Status, "deleted">
NonNullable<T>Strip null and undefined from a typeNonNullable<string | null> after a null check
ReturnType<T>Get the return type of a functionReturnType<typeof fetchUser> to type a variable
Parameters<T>Get the parameter types of a function as a tupleParameters<typeof handler>[0] for the first arg

Combine them for precision: Partial<Pick<User, "name" | "email">> for an optional name-and-email update.

Error Handling

Never throw from library or shared code. Use the Result pattern to make errors part of the type signature.

Result Type

typescript
type Result<T, E = Error> =
  | { ok: true; data: T }
  | { ok: false; error: E };

Apply it consistently:

typescript
type ValidationError = { field: string; message: string };
type AuthError = { code: "UNAUTHORIZED" | "FORBIDDEN"; message: string };

async function createUser(input: CreateUserInput): Promise<Result<User, ValidationError[]>> {
  const errors = validate(input);
  if (errors.length > 0) {
    return { ok: false, error: errors };
  }
  const user = await db.users.create(input);
  return { ok: true, data: user };
}

// Caller handles both paths explicitly
const result = await createUser(input);
if (!result.ok) {
  // result.error is typed as ValidationError[]
  return showErrors(result.error);
}
// result.data is typed as User
console.log(result.data.id);

Typed Error Hierarchies

Use discriminated unions for error types so callers can narrow:

typescript
type AppError =
  | { kind: "validation"; fields: { field: string; message: string }[] }
  | { kind: "not_found"; resource: string; id: string }
  | { kind: "unauthorized"; reason: string }
  | { kind: "internal"; message: string };

When to Throw

Throw only at application boundaries (request handlers, CLI entry points) where you convert Results into HTTP responses or exit codes. Never throw from utility functions, services, or domain logic.

Discriminated Unions

Use discriminated unions for any value that can be in one of several mutually exclusive states. Always use a kind, type, or status field as the discriminant.

State Machines

typescript
type RequestState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: AppError };

API Responses

typescript
type ApiResponse<T> =
  | { ok: true; data: T; meta: { requestId: string } }
  | { ok: false; error: { code: string; message: string; details?: unknown } };

Form States

typescript
type FormState =
  | { step: "input"; values: Partial<FormValues> }
  | { step: "review"; values: FormValues }
  | { step: "submitting"; values: FormValues }
  | { step: "complete"; result: SubmitResult }
  | { step: "error"; values: FormValues; error: string };

Exhaustiveness Checking

Always use a never check in switch statements to catch unhandled variants at compile time:

typescript
function assertNever(value: never): never {
  throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}

function renderState(state: RequestState<User>) {
  switch (state.status) {
    case "idle": return null;
    case "loading": return <Spinner />;
    case "success": return <Profile user={state.data} />;
    case "error": return <ErrorBanner error={state.error} />;
    default: return assertNever(state);
  }
}

Module Patterns

Barrel Exports

Use barrel exports (index.ts) sparingly. They hurt tree-shaking and create circular dependency risks. Prefer direct imports.

ScenarioUse Barrel?Why
Public API of a package/libraryYesProvides a stable import surface
Internal module groupingNoImport directly from the source file
Re-exporting types onlyYesTypes are erased at compile time, no bundle cost

Re-export Types

When a module's types are needed elsewhere but its runtime code is not, re-export types separately:

typescript
// types.ts — pure types, no runtime
export type { User, CreateUserInput, UserRole };

// index.ts — runtime exports
export { createUser, getUser, deleteUser };

Isolate Side Effects

Keep side effects (database connections, env reads, logging init) in dedicated files. Don't mix side-effect code with pure business logic:

typescript
// db.ts — side effect: opens connection
export const db = createConnection(process.env.DATABASE_URL);

// user-service.ts — pure, receives db as dependency
export function createUserService(db: Database) {
  return {
    findById(id: UserId): Promise<User | null> { /* ... */ },
  };
}

Anti-Patterns

Avoid these. When you encounter them in existing code, refactor.

Anti-PatternProblemDo Instead
anyDisables all type checkingUse unknown and narrow, or define the actual type
as type assertionsLies to the compilerUse type guards or discriminated unions to narrow
Non-null assertion !Hides potential null bugsCheck for null explicitly or use optional chaining
enumNon-standard JS, poor tree-shakingUse as const objects or string literal unions
Function typeAccepts anything callableUse specific signatures: (input: T) => R
Object / {}Matches almost everythingUse Record<string, unknown> or a specific interface
namespaceLegacy pattern, poor module compatUse ES modules
Overloads for unionsVerbose, hard to maintainUse a single signature with a discriminated union parameter
@ts-ignoreSilences real errorsFix the type error or use @ts-expect-error with a comment
Index signatures everywhereToo permissiveDefine explicit interfaces for known shapes

Поширені запитання

Що робить навичка ШІ Typescript Patterns?

TypeScript best practices and advanced type design patterns. Use when writing, reviewing, or refactoring TypeScript code. Covers type narrowing, generics, utility types, discriminated unions, error handling, and module patterns. Triggers on TypeScript, type safety, or type design tasks.

Навіщо використовувати Typescript Patterns у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Typescript Patterns — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Typescript Patterns у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/kazdenc/builder-skills/tree/main/.claude/skills/dev/frameworks/typescript-patterns. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Typescript Patterns?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Typescript Patterns?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Typescript Patterns — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Typescript Patterns?

Так. Навичку опубліковано на GitHub: kazdenc, за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇