Provides guidance and pattern matching for transitioning imperative or OOP code to functional TypeScript paradigms.

Install

mkdir -p .claude/skills/functype && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/14699" && unzip -o skill.zip -d .claude/skills/functype && rm skill.zip

Installs to .claude/skills/functype

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Help developers use functype functional programming patterns in their TypeScript projects. Use this skill when converting imperative/OOP code to functional patterns, looking up functype APIs and methods, handling nulls with Option, managing errors with Either/Try, composing effects with IO (lazy effects, typed errors, dependency injection, retry), working with immutable collections like List and Set, running async operations with Task, or making HTTP requests with Http (typed fetch wrapper).
496 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • →Convert imperative code to functional patterns
  • →Handle nullable values using Option types
  • →Manage errors with Either or Try types
  • →Compose effects with IO for lazy operations
  • →Work with immutable collections like List and Set

How it works

This skill helps developers refactor TypeScript code to use functype, a Scala-inspired functional programming library, by providing guidance on Option, Either, Try, List, and other functional types.

Inputs & outputs

You give it
TypeScript code with imperative patterns or null checks
You get back
TypeScript code refactored to use functype functional patterns

When to use functype

  • →Converting OOP classes to functional patterns
  • →Handling null values using Option types
  • →Implementing functional pipe patterns in TS

About this skill

Functype User Guide

Overview

Transform TypeScript code to use functype - a Scala-inspired functional programming library providing type-safe alternatives to null checks, exceptions, and imperative patterns. This skill helps integrate Option, Either, Try, List, IO, and other functional types into projects.

When to Use This Skill

Trigger this skill when users:

  • Convert imperative code to functional patterns
  • Look up functype APIs or methods
  • Handle nullable values or optional chaining
  • Replace try-catch with functional error handling
  • Work with immutable collections
  • Compose side effects, async operations, or dependency injection with IO
  • Run async operations with cancellation (IO's runCancellable, interruptOn)
  • Trace effects with nested spans (IO's withSpan, behind a type-only SpanTracer)
  • Debug functype code or understand error messages
  • Upgrade code from functype 1.x to 2.0: functype.org/upgrading-to-2 lists what to change

Quick Start

Installation

npm install functype
# or
pnpm add functype

Core Imports

// Import from main bundle
import { Option, Either, Left, Right, Try, List, IO, Tag, Layer } from "functype"

Constructor vs Companion Methods

Functype collections provide multiple ways to create instances:

MethodUse WhenExample
List([...])Creating from existing arrayList(existingArray)
List.of(...)Inline literal valuesList.of(1, 2, 3)
List.empty()Empty collections (typed)List.empty<number>()

Decision Guide

Use Constructor List([...]) when:

  • Converting existing arrays: List(data.items)
  • Spreading iterables: List([...set])
  • Variables holding arrays: List(myArray)

Use List.of(...) when:

  • Inline literal values: List.of(1, 2, 3)
  • Cleaner for small fixed lists: List.of("a", "b", "c")
  • No need to wrap in array brackets

Use List.empty() when:

  • Starting with empty collection: List.empty<User>()
  • Type parameter needed but no initial values
  • Returns singleton (efficient for repeated calls)

Examples

// Constructor - wrapping existing data
const users = List(fetchedUsers)
const items = List([...existingSet])

// .of() - inline literals
const colors = List.of("red", "green", "blue")
const primes = Set.of(2, 3, 5, 7, 11)

// .empty() - typed empty collections
const errors = List.empty<string>()
const cache = Map.empty<string, User>()

Pattern Conversion Guide

Null/Undefined Checks → Option

Before (Imperative):

function shout(name: string | null | undefined): string {
  if (name !== null && name !== undefined) {
    return name.toUpperCase()
  }
  return ""
}

After (Functype):

const shout = (name: string | null | undefined): string =>
  Option(name)
    .map((v) => v.toUpperCase())
    .getOrElse(() => "")

Optional Chaining → Option Chain

Before:

const url = user?.profile?.avatar?.url

After:

const url = Option(user)
  .flatMap((u) => Option(u.profile))
  .flatMap((p) => Option(p.avatar))
  .map((a) => a.url)
  .getOrElse(() => "/default-avatar.png")

Try-Catch → Try or Either

Before:

function parse(str: string): unknown {
  try {
    return JSON.parse(str)
  } catch {
    return null
  }
}

After (with Try):

Try(() => JSON.parse(str))
  .toOption()
  .getOrElse(() => null)

After (with Either):

Try(() => JSON.parse(str) as unknown)
  .toEither((error) => error)
  .fold(
    (error) => `Parse failed: ${error.message}`,
    (data) => data,
  )

Array Operations → List

Before:

array.filter((x) => x > 0).map((x) => x * 2)

After:

List(array)
  .filter((x) => x > 0)
  .map((x) => x * 2)
  .toArray()

If-Else Chains → Cond

Before:

function size(x: number): string {
  if (x > 10) {
    return "big"
  } else if (x > 5) {
    return "medium"
  } else {
    return "small"
  }
}

After:

import { Cond } from "functype"

const size = (x: number): string =>
  Cond.of<string>()
    .when(x > 10, "big")
    .elseWhen(x > 5, "medium")
    .else("small")

Switch Statements → Match

Before:

function describe(status: "success" | "error"): string {
  switch (status) {
    case "success":
      return "done"
    case "error":
      return "failed"
  }
}

After:

import { Match } from "functype"

const describe = (status: "success" | "error"): string =>
  Match(status)
    .case("success", () => "done")
    .case("error", () => "failed")
    .exhaustive()

Common Use Cases

Validation with Either

import { Either, Left, Right } from "functype"

function validateEmail(email: string): Either<string, string> {
  return email.includes("@") ? Right(email) : Left("Invalid email format")
}

type SignupInput = { readonly email: string; readonly age: number }

function validateUser(input: SignupInput): Either<string, SignupInput> {
  return validateEmail(input.email)
    .map((email) => ({ ...input, email }))
    .flatMap((u) => (u.age >= 18 ? Right(u) : Left("Must be 18 or older")))
}

const result = validateUser({ email: "[email protected]", age: 20 }).fold(
  (error) => console.error(error),
  (user) => console.log("Valid user:", user),
)

Safe API Calls with Option

import { Option } from "functype"

interface User {
  id: string
  name: string
  email?: string
}

function getUserEmail(userId: string): Option<string> {
  return Option(findUser(userId))
    .flatMap((user) => Option(user.email))
    .filter((email) => email.includes("@"))
}

const email = getUserEmail("123").getOrElse(() => "[email protected]")

Error Recovery with Try

import { Try } from "functype"

const parseConfig = Try(() => JSON.parse(configStr))
  .recover((error) => {
    console.warn("Using default config:", error)
    return defaultConfig
  })
  .map((config) => validateConfig(config))

Collection Pipeline with List

import { List } from "functype"

const users = List([
  { name: "Alice", hobbies: ["reading", "coding"] },
  { name: "Bob", hobbies: ["gaming", "music"] },
])

const allHobbies = users
  .flatMap((user) => List(user.hobbies))
  .toSet() // Remove duplicates
  .toArray()

Additional Data Structures

IO<R,E,A> - Effect Type

IO is a lazy, composable effect type with typed errors and dependency injection:

  • R = Requirements (environment/dependencies needed)
  • E = Error type (typed failures)
  • A = Success type (value produced on success)
import { IO, Tag, Layer } from "functype"

// Creation
IO.sync(() => computation()) // Sync operation
IO.succeed(value) // Pure success
IO.fail(error) // Pure failure
IO.async(() => promise) // Async operation
IO.tryPromise({
  // Promise with error mapping
  try: () => fetch(url),
  catch: (e) => new NetworkError(e),
})

// Dependency injection
const Database = Tag<DatabaseService>("Database")
const dbEffect = IO.service(Database) // Access a service
const program = dbEffect.flatMap((db) => IO.sync(() => db.query()))
program.provideLayer(Layer.succeed(Database, myDb)) // Provide deps

// Generator do-notation (cleaner syntax)
const findProgram = IO.gen(function* () {
  const db = yield* IO.service(Database)
  const user = yield* IO.async(() => db.findUser(id))
  return user
})

// Execution
await effect.run() // Returns Promise<Either<E, A>>; the Left is always an E. A defect or interruption rejects (2.0)
await effect.runOrThrow() // Returns Promise<A>; rejects with the error
effect.runSync() // Returns Either<E, A>; throws a defect, an interruption, or an async/timeout/race/sleep effect
await effect.runExit() // Returns Promise<Exit<E, A>>

// Tracing (2.0): withSpan runs an effect in a span; an inner withSpan nests under it without a
// parent. functype ships only the SpanTracer contract and no tracer, so with none provided withSpan
// does nothing. Provide yours (an OpenTelemetry bridge is a few lines) outside the spans.
const tracer: SpanTracer<string> = { start: (name) => name, run: (_span, fn) => fn(), end: () => undefined }
await effect.withSpan("load", { "user.id": id }).provideService(SpanTracer, tracer).run()

// run() vs runExit(): Either has two branches, Exit has four. Use run() when the Left is
// all you handle; use runExit() to tell a typed failure from a *defect* (a value that is
// not an E — a throwing IO.sync thunk or map/mapError callback, or IO.die) or from an
// interruption without a try. run() rejects on both: the raw defect, or an InterruptedError.
const exit = await effect.runExit()
exit.isSuccess() // completed with a value
exit.isFailure() // a value from the declared E channel
exit.isDie() // a defect — NOT an E
exit.isInterrupted() // cancelled
if (exit.isSuccess()) exit.value // each guard narrows to its field: .value / .error / .defect / .fiberId

// Both extra handlers are optional and fall back to the failure branch, so existing
// three-argument fold / three-key match calls keep working.
exit.fold(onFailure, onSuccess) // optional 3rd and 4th handlers: onInterrupted, onDie
exit.match({ Success: onSuccess, Failure: onFailure, Interrupted: onInterrupted }) // Die is optional

// Defects stay recoverable: recover / recoverWith / fold / mapError treat a Die exactly
// as a Failure. Exit.Die records what the outcome was when nothing recovered it.

Tuple - Type-safe Fixed-length Array

import { Tuple } from "functype"

const pair = Tuple([42, "hello"] as [number, string]) // Tuple takes one array
pair.get(0) // 42
pair.get(1) // "hello"
pair.map(([a, b])

---

*Content truncated.*

When not to use it

  • →When the user prefers imperative or OOP patterns
  • →When the task does not involve functional programming concepts

Prerequisites

functype

Limitations

  • →Requires installation of the functype library.
  • →Focuses on Scala-inspired functional programming patterns.
  • →Requires understanding of functional programming concepts.

How it compares

This skill provides specific guidance and examples for converting common imperative patterns into type-safe functional constructs using functype, offering a structured approach to adopting functional programming in TypeScript.

Compared to similar skills

functype side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
functype (this skill)05moReviewAdvanced
typescript-expert1010moReviewAdvanced
agent-coder39moNo flagsIntermediate
functional35moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

Search skills

Search the agent skills registry