Provides functype functional programming patterns for TypeScript: Option, Either, Try, IO, List, and Http. Helps convert imperative/OOP code, handle nulls, manage errors, compose effects, and work with immutable collections.
Ships in functype. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
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.
Trigger this skill when users:
runCancellable, interruptOn)withSpan, behind a type-only SpanTracer)npm install functype
# or
pnpm add functype
// Import from main bundle
import { Option, Either, Left, Right, Try, List, IO, Tag, Layer } from "functype"
functype collections provide multiple ways to create instances:
| Method | Use When | Example |
|---|---|---|
List([...]) | Creating from existing array | List(existingArray) |
List.of(...) | Inline literal values | List.of(1, 2, 3) |
List.empty() | Empty collections (typed) | List.empty<number>() |
Use Constructor List([...]) when:
List(data.items)List([...set])List(myArray)Use List.of(...) when:
List.of(1, 2, 3)List.of("a", "b", "c")Use List.empty() when:
List.empty<User>()// 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>()
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(() => "")
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")
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,
)
Before:
array.filter((x) => x > 0).map((x) => x * 2)
After:
List(array)
.filter((x) => x > 0)
.map((x) => x * 2)
.toArray()
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")
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()
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),
)
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]")
import { Try } from "functype"
const parseConfig = Try(() => JSON.parse(configStr))
.recover((error) => {
console.warn("Using default config:", error)
return defaultConfig
})
.map((config) => validateConfig(config))
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()
IO is a lazy, composable effect type with typed errors and dependency injection:
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
// The typed error operators (recover / recoverWith / fold / mapError / catchTag / catchAll /
// tapError / retry) see only a Failure: a Die passes them unchanged, so a crash stays a crash.
// Opt in with io.catchDefect((defect) => ...). To make a throw a typed failure, build the
// effect with IO(() => ...) or IO.tryCatch, not IO.sync.
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]) => [a * 2, b] as [number, string]) // Tuple([84, "hello"])
pair.map(([a, b]) => [b, a] as [string, number]) // swap: Tuple(["hello", 42])
pair.get(0) + pair.get(1).length // 47
pair.flatMap(([a, b]) => Tuple([a, b, true] as [number, string, boolean])) // Tuple([42, "hello", true])
import { Stack } from "functype"
Stack.empty<number>()
const stack = Stack.of(1, 2, 3) // same as Stack([1, 2, 3])
stack.push(4) // Returns new Stack
stack.pop() // Returns [Option<T>, Stack<T>]
stack.peek() // Returns Option<T>
stack.match({
Empty: () => "empty stack",
NonEmpty: (values) => `${values.length} items`,
})
import { LazyList } from "functype"
// Creation
LazyList([1, 2, 3])
LazyList.of(1, 2, 3)
LazyList.empty<number>()
// Infinite sequences
const naturals = LazyList.iterate(0, (n) => n + 1)
const evens = naturals.filter((n) => n % 2 === 0).take(10)
// Operations are deferred until needed
const result = LazyList(hugeArray)
.filter((x) => x > 0)
.map((x) => x * 2)
.take(5)
.toArray() // Only processes first 5 matching elements
Scala-like for-comprehensions using JavaScript generators:
import { Do, DoAsync, $ } from "functype"
// Synchronous comprehensions
const result = Do(function* () {
const x = yield* $(Option(5))
const y = yield* $(Option(10))
return x + y
}) // Option(15)
// Async comprehensions
const asyncResult = await DoAsync(async function* () {
const user = yield* $(await fetchUserAsync(userId))
const profile = yield* $(await fetchProfileAsync(user.id))
return { user, profile }
})
// Cartesian products with List (2.5x-12x faster than nested flatMap)
const pairs = Do(function* () {
const x = yield* $(List([1, 2, 3]))
const y = yield* $(List([10, 20]))
return { x, y }
}) // List([{x:1,y:10}, {x:1,y:20}, {x:2,y:10}, ...])
// Mixed monad types with automatic conversion
const mixed = Do(function* () {
const a = yield* $(Option(5))
const b = yield* $(Right<string, number>(10))
return a + b
})
Note: First monad determines return type. Uses Reshapeable for automatic type conversion.
All types provide static type guards for narrowing:
import { Option, Either, Try } from "functype"
// Option type guards
if (Option.isSome(option)) {
option.value // TypeScript knows value exists
}
if (Option.isNone(option)) {
// Handle empty case
}
// Either type guards
if (Either.isRight(either)) {
either.value // TypeScript knows it's Right
}
if (Either.isLeft(either)) {
either.value // TypeScript knows it's error value
}
// Try type guards
if (Try.isSuccess(tryVal)) {
tryVal.value // TypeScript knows it's the success value
tryVal.error // TypeScript knows: undefined
}
if (Try.isFailure(tryVal)) {
tryVal.error // TypeScript knows it failed
}
All Serializable types provide JSON and binary serialization (2.0 removed YAML):
// Serialization methods
option.serialize().toJSON()
option.serialize().toBinary() // Uint8Array
// Deserialization
Option.fromJSON<string>(jsonString)
Option.fromBinary<string>(binaryData)
Since 2.0 there is one preset, recommended, and every rule in it is an error or off: an agent acts on a failed build and passes over a warning. Twenty rules are errors; only prefer-flatmap and prefer-do-notation are off. functype.configs.tests relaxes a few for test files.
The type-aware rules need parserOptions.projectService, and they catch bugs that compile. Each message names the fix:
no-uncalled-method: list.head without () reads the method itself. Call it: list.head() or list.headOption().no-floating-result: an Either or Try that's dropped loses its failure. Return it, fold it, or mark a deliberate drop with void.no-floating-io: an IO that's built and never run does nothing. Run it, return it, or yield* it.no-serialize-container: an Either or Option sent to c.json() or JSON.stringify sends its envelope. Unwrap it first.no-container-mutation: a write to a functype value through a cast. Build a new value instead. Collections also freeze each value under NODE_ENV=development (or FUNCTYPE_FREEZE=1), so such a write throws there.no-array-mutation: push, sort or xs[i] = v changes an array in place. Build a new one.Write code that passes, and when code is correct because it isn't FP-shaped, declare the boundary instead of disabling the rule:
| Situation | Do this | Not this |
|---|---|---|
DB row / HTTP body / JSONB with null fields or arrays | type UserRow = Wire<{ email: string | null; tags: ReadonlyArray<string> }> | eslint-disable on each field |
| A collection at a boundary | Wire<ReadonlyArray<Row>> (not Wire<Row>, which is one row) | Row[] |
| A patch field that can be left out, cleared or set | type Clearable<T> = Wire<T | null | undefined> (undefined keeps, null removes, a value replaces) | Option<T>, which has only two states |
A type inferred from a schema (z.infer, valibot, a decoder) | Wrap the alias in Wire<…>, and convert a field to Option where code first decides from it | eslint-disable on the alias |
| A function result your code reads | Option<T>, converted once from the driver's row or undefined | Wire<T | null> flowing past the first function that decides from it |
A bridge whose host requires a throw / rejection / nullable (React use(), React Query, a nullable→Option converter) | JSDoc @interop <reason> on the function | file-level eslint-disable |
| A throw for a programmer error, not an expected failure | invariant(cond, "msg") — narrows cond after it | throw (reported), Either for an impossible case, or a disable |
| A host needs a throw built from the failure | either.orThrow((l) => new StepError(l.message)) | throw inside a fold |
| React state that may be empty | useState<User | null>(null) — allowed as-is | Option inside hook state |
Any Map / Set | import { Map, Set } from "functype" — functype's own names. Map in a file that imports it means functype's | Map as FMap, new Map() on functype's factory (it isn't a class) |
The built-in is genuinely needed: a cache mutated on purpose, or a value for an API typed ReadonlyMap | new globalThis.Map() / new globalThis.Set() — allowed when mutated or passed to a declared ReadonlyMap/ReadonlySet | bare new Map() in a file that imports functype's Map (TS7009, or TS2350 without noImplicitAny) |
| Loop that awaits, one call at a time | List(items).mapAsync(f); Either.traverseAsync(items, f) when f returns Either (stops at the first Left); IO.forEach(items, f) inside IO | .forEach with an async callback, or a reduce over promises |
Reading code: in a file with import { Map } from "functype", every Map is functype's (immutable, built with Map(…)), and the built-in is always written globalThis.Map. With no functype import, Map is the built-in — check the imports before assuming.
@interop needs a reason on the same line (@interop React Query needs a rejection.); a bare tag exempts nothing. It covers the tagged declaration and what is nested inside it. Rule of thumb: host needs the throw → @interop or orThrow(builder); only a bug can trip it → invariant(); can fail in normal operation → Either.
For a complete overview of which methods are available on each data structure, consult the Feature Matrix at:
references/feature-matrix.md (included with this skill)packages/functype/docs/FUNCTYPE_FEATURE_MATRIX.mdThe matrix shows which interfaces (Functor, Monad, Foldable, etc.) each type implements and what methods are available.
Option
map, flatMap, filter, foldgetOrElse, orElse, orNull, orUndefined, orThrowisSome, isNone, containsEither<L, R>
map, flatMap, foldgetOrElse, orElse, swapisLeft, isRightTry
map, flatMap, foldrecover, recoverWithtoOption, toEitherisSuccess, isFailuremap, flatMap, filter, reducefoldLeft, foldRightadd, prepend, concathead, tail, isEmptytoArray, toSetFor pattern conversion help, examples, and API reference:
references/feature-matrix.md for complete interface/method referencenpx functype for LLM-optimized API reference"Type 'X' is not assignable to type 'Y'"
Option<string> not Option<any>"Cannot read property 'map' of undefined"
Option(value) not just valueList([...]), Right(value)Forgetting to extract values
// Wrong - returns Option<string>
const wrapped = Option(user).map((u) => u.name)
// Correct - returns string
const name = Option(user)
.map((u) => u.name)
.getOrElse(() => "Unknown")
Using map instead of flatMap
// Wrong - returns Option<Option<string>>
Option(user).map((u) => Option(u.email))
// Correct - returns Option<string>
Option(user).flatMap((u) => Option(u.email))
Mutating instead of transforming
// Wrong - mutates original array
const list = List([1, 2, 3])
list.toArray().push(4)
// Correct - creates new List
const newList = list.add(4)
feature-matrix.md - Complete interface and method referencecommon-patterns.md - Additional pattern examples and recipesquick-reference.md - Cheat sheet for functype APIsFor more examples and detailed documentation, visit:
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/functype:functypefrom functype
npx claudepluginhub jordanburke/functype --plugin functypeOther plugins' skills for the same job