Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计未展示

typescript%3afunctional-patternsTypeScript 3afunctional 模式

Agent Skill

typescript%3afunctional-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

196

周安装

8

GitHub Stars

20

下载量

63
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/martinffx/atelier --skill typescript:functional-patterns

简介

用于查找、检索和筛选相关信息,支持基于关键词快速定位候选结果。

  • 适用于 Codex、Claude、Cursor、Gemini CLI 中的研究检索类任务场景。
  • 通过 GitHub 安装,使用 npx skills add 命令从 martinffx/atelier 仓库添加技能。
  • 安装前应检查权限范围和维护状态,确认是否涉及联网或文件读写操作。
  • typescript%3afunctional-patterns 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Functional Patterns for Reliable TypeScript

Build reliable systems using Algebraic Data Types (ADTs), discriminated unions, Result/Option types, and branded types. These patterns enable the compiler to prove correctness, prevent runtime errors, and make illegal states unrepresentable.

Why Functional Patterns?

Reliability through types: Use the type system to encode business rules, making invalid states impossible to construct. The compiler becomes your safety net, catching errors at build time rather than runtime.

Key benefits:

  • Exhaustiveness checking prevents missing cases
  • Impossible states become unrepresentable
  • Business logic encoded in types, not runtime checks
  • Refactoring becomes safe and mechanical
  • Self-documenting code through types

Quick Reference

For detailed patterns and examples, see:

Core Patterns Overview

1. Discriminated Unions (Sum Types)

Model "one of several variants" with exhaustive pattern matching:

type PaymentMethod =
  | { kind: "card"; last4: string; brand: string }
  | { kind: "ach"; accountNumber: string; routingNumber: string }
  | { kind: "wallet"; provider: "apple" | "google" }

function processPayment(method: PaymentMethod): void {
  switch (method.kind) {
    case "card":
      // TypeScript knows: method.last4 and method.brand exist
      return processCard(method.last4, method.brand)
    case "ach":
      // TypeScript knows: method.accountNumber and method.routingNumber exist
      return processACH(method.accountNumber, method.routingNumber)
    case "wallet":
      // TypeScript knows: method.provider exists
      return processWallet(method.provider)
    default:
      assertNever(method) // Compiler error if cases missing
  }
}

2. Option Type (Nullable Values)

Explicit handling of "value may be absent":

type Option<T> = { _tag: "None" } | { _tag: "Some"; value: T }

function findUser(id: string): Option<User> {
  const user = database.get(id)
  return user ? Some(user) : None
}

const result = findUser("123")
switch (result._tag) {
  case "Some":
    console.log(result.value.name) // Type-safe access
    break
  case "None":
    console.log("User not found")
    break
}

3. Result Type (Error Handling)

Explicit error handling without exceptions:

type Result<T, E> = { _tag: "Ok"; value: T } | { _tag: "Err"; error: E }

function parseConfig(raw: string): Result<Config, ParseError> {
  try {
    const data = JSON.parse(raw)
    return Ok(validateConfig(data))
  } catch (e) {
    return Err({ message: "Invalid JSON", cause: e })
  }
}

const result = parseConfig(rawConfig)
switch (result._tag) {
  case "Ok":
    startServer(result.value)
    break
  case "Err":
    logger.error(result.error.message)
    break
}

4. Branded Types (Type-Safe Units)

Prevent unit confusion and invalid values:

type Brand<K, T> = K & { __brand: T }
type Cents = Brand<number, "Cents">
type Dollars = Brand<number, "Dollars">

const Cents = (n: number): Cents => {
  if (!Number.isInteger(n) || n < 0) throw new Error("Invalid cents")
  return n as Cents
}

const Dollars = (n: number): Dollars => {
  if (n < 0) throw new Error("Invalid dollars")
  return n as Dollars
}

// Compiler prevents mixing units:
const price: Cents = Cents(100)
const budget: Dollars = Dollars(10)
const total: Cents = price + budget // Type error! Cannot mix Cents and Dollars

When to Use

Use Discriminated Unions When:

  • Modeling state machines (pending → settled → reconciled)
  • Representing mutually exclusive variants (payment methods, user roles)
  • Building domain models with distinct states
  • Replacing boolean flags with explicit states

Use Option When:

  • Value may be absent (but absence is expected/valid)
  • Replacing null or undefined checks
  • Chaining operations that may fail to find values
  • Making nullability explicit in APIs

Use Result When:

  • Operation may fail with recoverable errors
  • You need to propagate error context
  • Replacing try/catch for expected failures
  • Building error handling into function signatures

Use Branded Types When:

  • Preventing unit confusion (cents vs dollars, ms vs seconds)
  • Enforcing validation invariants (email format, positive numbers)
  • Creating type-safe IDs (UserId vs OrderId)
  • Domain-driven design with value objects

Quick Start - Paste-Ready Helpers

Copy these into your project to start using functional patterns:

// ============================================
// Option Type
// ============================================
type None = { _tag: "None" }
type Some<T> = { _tag: "Some"; value: T }
type Option<T> = None | Some<T>

const None: None = { _tag: "None" }
const Some = <T>(value: T): Option<T> => ({ _tag: "Some", value })

// Utilities
const isNone = <T>(opt: Option<T>): opt is None => opt._tag === "None"
const isSome = <T>(opt: Option<T>): opt is Some<T> => opt._tag === "Some"

const getOrElse = <T>(opt: Option<T>, defaultValue: T): T =>
  opt._tag === "Some" ? opt.value : defaultValue

const map = <T, U>(opt: Option<T>, fn: (value: T) => U): Option<U> =>
  opt._tag === "Some" ? Some(fn(opt.value)) : None

const flatMap = <T, U>(opt: Option<T>, fn: (value: T) => Option<U>): Option<U> =>
  opt._tag === "Some" ? fn(opt.value) : None

// ============================================
// Result Type
// ============================================
type Ok<T> = { _tag: "Ok"; value: T }
type Err<E> = { _tag: "Err"; error: E }
type Result<T, E> = Ok<T> | Err<E>

const Ok = <T>(value: T): Result<T, never> => ({ _tag: "Ok", value })
const Err = <E>(error: E): Result<never, E> => ({ _tag: "Err", error })

// Utilities
const isOk = <T, E>(result: Result<T, E>): result is Ok<T> => result._tag === "Ok"
const isErr = <T, E>(result: Result<T, E>): result is Err<E> => result._tag === "Err"

const mapResult = <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> =>
  result._tag === "Ok" ? Ok(fn(result.value)) : result

const flatMapResult = <T, U, E>(
  result: Result<T, E>,
  fn: (value: T) => Result<U, E>
): Result<U, E> =>
  result._tag === "Ok" ? fn(result.value) : result

// ============================================
// Exhaustiveness Checking
// ============================================
const assertNever = (x: never): never => {
  throw new Error(`Unhandled variant: ${JSON.stringify(x)}`)
}

// ============================================
// Branded Types
// ============================================
type Brand<K, T> = K & { __brand: T }

// Example: Cents (integer cents to prevent floating point errors)
type Cents = Brand<number, "Cents">
const Cents = (n: number): Cents => {
  if (!Number.isInteger(n)) throw new Error("Cents must be integer")
  if (n < 0) throw new Error("Cents cannot be negative")
  return n as Cents
}

// Example: Email (validated email address)
type Email = Brand<string, "Email">
const Email = (s: string): Email => {
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)) throw new Error("Invalid email")
  return s as Email
}

// Example: Millis (timestamp in milliseconds)
type Millis = Brand<number, "Millis">
const Millis = (n: number): Millis => {
  if (n < 0) throw new Error("Millis cannot be negative")
  return n as Millis
}

Guidelines

Pattern Matching Best Practices

  1. Always use assertNever in default case for exhaustiveness checking: switch (variant.kind) {case "a": return handleA(variant) case "b": return handleB(variant) default: assertNever(variant) // Compiler error if cases missing}
  2. Use discriminant field consistently (kind, type, _tag): // Good: consistent discriminant type Result<T, E> = {_tag: "Ok"; value: T} | {_tag: "Err"; error: E} // Avoid: mixing discriminants type Bad = {kind: "a"} | {type: "b"} // Inconsistent!
  3. Narrow types early to unlock type safety: if (result._tag === "Ok") {// TypeScript knows: result.value exists return result.value.data}

Error Handling Strategy

  1. Use Option for expected absence: function findUser(id: string): Option<User>
  2. Use Result for recoverable errors: function parseConfig(raw: string): Result<Config, ParseError>
  3. Use exceptions for programmer errors: ` function unreachable(message: string): never {throw new Error(Unreachable: ${message})} `

Branded Types Guidelines

  1. Validate in smart constructor: const PositiveInt = (n: number): PositiveInt => {if (!Number.isInteger(n) || n <= 0) throw new Error("Must be positive integer") return n as PositiveInt}
  2. Use branded types for domain concepts: type UserId = Brand<string, "UserId"> type OrderId = Brand<string, "OrderId"> // Compiler prevents: const userId: UserId = orderId
  3. Prevent unit confusion: type Seconds = Brand<number, "Seconds"> type Millis = Brand<number, "Millis"> // Compiler prevents: const s: Seconds = millis

Migration Strategy

Start small and expand:

  1. New features: Use functional patterns from day one
  2. Bug fixes: Refactor to discriminated unions when touching code
  3. High-risk areas: Prioritize financial calculations, state machines
  4. Team adoption: Share paste-ready helpers, pair on first implementations

Enable TypeScript strict mode flags:

  • strictNullChecks: true - Make nullability explicit
  • noImplicitReturns: true - Ensure all code paths return
  • strictFunctionTypes: true - Safer function signatures

Examples by Domain

State Machine (Transaction Lifecycle)

type TxnState =
  | { kind: "pending"; createdAt: Millis }
  | { kind: "settled"; ledgerId: string; settledAt: Millis }
  | { kind: "failed"; reason: FailureReason; failedAt: Millis }
  | { kind: "reversed"; originalLedgerId: string; reversedAt: Millis }

function canReverse(state: TxnState): boolean {
  switch (state.kind) {
    case "pending": return false
    case "settled": return true
    case "failed": return false
    case "reversed": return false
    default: assertNever(state)
  }
}

Configuration Parsing

type ConfigError = { field: string; message: string }

function parsePort(raw: unknown): Result<number, ConfigError> {
  if (typeof raw !== "number") {
    return Err({ field: "port", message: "must be number" })
  }
  if (raw < 1 || raw > 65535) {
    return Err({ field: "port", message: "must be 1-65535" })
  }
  return Ok(raw)
}

Financial Calculations

type Cents = Brand<number, "Cents">

function addCents(a: Cents, b: Cents): Cents {
  return Cents(a + b) // Smart constructor validates result
}

function calculateFee(amount: Cents, bps: number): Cents {
  const feeAmount = Math.round((amount * bps) / 10000)
  return Cents(feeAmount)
}

Further Reading

Credits

These patterns are inspired by Why Reliability Demands Functional Programming, ADTs, Safety and Critical Infrastructure by Rastrian. The blog post explores how functional programming techniques and Algebraic Data Types enable building reliable systems in critical infrastructure contexts.

When This Skill Loads

This skill automatically loads when discussing:

  • Discriminated unions and sum types
  • State machine modeling
  • Result/Option types and error handling
  • Branded types and smart constructors
  • Type-safe domain models
  • Making illegal states unrepresentable
  • Functional programming in TypeScript

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

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

平台分布

Codex

38.01%
按下载量换算24

Claude

30.12%
按下载量换算19

Cursor

20.08%
按下载量换算13

Gemini CLI

9.61%
按下载量换算6

安全审计

暂无安全审计结果可展示。

权限和风险

需要联网

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

安装前确认

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

来源信息

继续浏览同类 Skills