functype
/functype
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).
- Author
- jordanburke ↗
- Repository
- functype ↗
- Licence
- MIT
- Last repository change
- 26.10.2026
Assessment and security
- Files in this package
- 4
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 4
No signals detected. Repository changed on 26.10.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
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).
Original author description
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).
How it works
- Overview
- When to Use This Skill
- Quick Start
- Constructor vs Companion Methods
- Pattern Conversion Guide
- Common Use Cases
- Additional Data Structures
- Do-Notation (Generator Comprehensions)
- Companion Pattern & Type Guards
- Serialization
SKILL.md preview
---
name: functype
description: 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).
---
# 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, Task, 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 or progress tracking (Task)
- Debug functype code or understand error messages
## Quick Start
### Installation
```bash
npm install functype
# or
pnpm add functype
```
### Core Imports
```typescript
// Import from main bundle
import { Option, Either, Left, Right, Try, List, IO, Tag, Task, Layer } from "functype"
```
## Constructor vs Companion Methods
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>()` |
### 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
```typescript
// 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):**
```typescript
function shout(name: string | null | undefined): string {
if (name !== null && name !== undefined) {
return name.toUpperCase()
}
return ""
}
```
**After (Functype):**
```typescript
const shout = (name: string | null | undefined): string =>
Option(name)
.map((v) => v.toUpperCase())
.orElse("")
```
### Optional Chaining → Option Chain
**Before:**
```typescript
const url = user?.profile?.avatar?.url
```
**After:**
```typescript
const url = Option(user)
.flatMap((u) => Option(u.profile))
.flatMap((p) => Option(p.avatar))
.map((a) => a.url)
.orElse("/default-avatar.png")
```
### Try-Catch → Try or Either
**Before:**
```typescript
function parse(str: string): unknown {
try {
return JSON.parse(str)
} catch {
return null
}
}
```
**After (with Try):**
```typescript
Try(() => JSON.parse(str))
.toOption()
.orElse(null)
```
**After (with Either):**
```typescript
Try(() => JSON.parse(str) as unknown)
.toEither((error) => error)
.fold(
(error) => `Parse failed: ${error.message}`,
(data) => data,
)
```
### Array Operations → List
**Before:**
```typescript
array.filter((x) => x > 0).map((x) => x * 2)
```
**After:**
```typescript
List(array)
.filter((x) => x > 0)
.map((x) => x * 2)
.toArray()
```
### If-Else Chains → Cond
**Before:**
```typescript
function size(x: number): string {
if (x > 10) {
return "big"
} else if (x > 5) {
return "medium"
} else {
return "small"
}
}
```
**After:**
```typescript
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:**
```typescript
function describe(status: "success" | "error"): string {
switch (status) {
case "success":
return "done"
case "error":
return "failed"
}
}
```
**After:**
```typescript
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
```typescript
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: "test@example.com", age: 20 }).fold(
(error) => console.error(error),
(user) => console.log("Valid user:", user),
)
```
### Safe API Calls with Option
```typescript
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").orElse("no-reply@example.com")
```
### Error Recovery with Try
```typescript
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
```typescript
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)
```typescript
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>>
await effect.runOrThrow() // Returns Promise<A>; rejects with the error
effect.runSync() // Returns Either<E, A>; Left if the effect is async (runSyncOrThrow throws instead)
await effect.runExit() // Returns Promise<Exit<E, A>>
// run() vs runExit(): Either has two branches, Exit has four. Use run() when all you
// need is success-or-not; 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. run() puts both in the Left, raw.
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
```typescript
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])
```
### Stack - Last-In-First-Out Collection
```typescript
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`,
})
```
### LazyList - Lazy-evaluated List
```typescript
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
```
## Do-Notation (Generator Comprehensions)
Scala-like for-comprehensions using JavaScript generators:
```typescript
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.
## Companion Pattern & Type Guards
All types provide static type guards for narrowing:
```typescript
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.orThrow() // safe here: it succeeded (Try has no .value until 2.0)
tryVal.error // TypeScript knows: undefined
}
if (Try.isFailure(tryVal)) {
tryVal.error // TypeScript knows it failed
}
```
## Serialization
All Serializable types provide JSON, YAML, and binary serialization:
```typescript
// Serialization methods
option.serialize().toJSON()
option.serialize().toYAML()
option.serialize().toBinary() // Uint8Array
// Deserialization
Option.fromJSON<string>(jsonString)
Option.fromYAML<string>(yamlString)
Option.fromBinary<string>(binaryData)
```
## Lint Conventions (eslint-plugin-functype)
`recommended` **errors** on `no-let`, `no-imperative-loops`, `prefer-map`, `prefer-fold`, `prefer-functype-map`, `prefer-functype-set` and `collection-naming`. `prefer-option`, `prefer-either` and `prefer-try` warn. 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 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`.
## Looking Up Functype APIs
### Feature Matrix Reference
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)
- Or in the functype repo: `packages/functype/docs/FUNCTYPE_FEATURE_MATRIX.md`
The matrix shows which interfaces (Functor, Monad, Foldable, etc.) each type implements and what methods are available.
### Common Methods by Type
**Option<T>**
- `map`, `flatMap`, `filter`, `fold`
- `orElse`, `or`, `orNull`, `orUndefined`, `orThrow`
- `isSome`, `isNone`, `contains`
**Either<L, R>**
- `map`, `flatMap`, `fold`
- `orElse`, `or`, `swap`
- `isLeft`, `isRight`
**Try<T>**
- `map`, `flatMap`, `fold`
- `recover`, `recoverWith`
- `toOption`, `toEither`
- `isSuccess`, `isFailure`
**List<A>**
- `map`, `flatMap`, `filter`, `reduce`
- `foldLeft`, `foldRight`
- `add`, `prepend`, `concat`
- `head`, `tail`, `isEmpty`
- `toArray`, `toSet`
## Additional Resources
For pattern conversion help, examples, and API reference:
- **Feature Matrix**: See `references/feature-matrix.md` for complete interface/method reference
- **API Documentation**: https://jordanburke.github.io/functype/
- **GitHub Repository**: https://github.com/jordanburke/functype
- **CLI Documentation**: Run `npx functype` for LLM-optimized API reference
## Debugging Tips
### Understanding Error Messages
**"Type 'X' is not assignable to type 'Y'"**
- Ensure proper type parameters: `Option<string>` not `Option<any>`
- Check that chains maintain type consistency
**"Cannot read property 'map' of undefined"**
- Remember to construct the type: `Option(value)` not just `value`
- Some types require explicit constructors: `List([...])`, `Right(value)`
### Common Pitfalls
1. **Forgetting to extract values**
```typescript
// Wrong - returns Option<string>
const wrapped = Option(user).map((u) => u.name)
// Correct - returns string
const name = Option(user)
.map((u) => u.name)
.orElse("Unknown")
```
2. **Using map instead of flatMap**
```typescript
// Wrong - returns Option<Option<string>>
Option(user).map((u) => Option(u.email))
// Correct - returns Option<string>
Option(user).flatMap((u) => Option(u.email))
```
3. **Mutating instead of transforming**
```typescript
// Wrong - mutates original array
const list = List([1, 2, 3])
list.toArray().push(4)
// Correct - creates new List
const newList = list.add(4)
```
## Resources
### references/
- `feature-matrix.md` - Complete interface and method reference
- `common-patterns.md` - Additional pattern examples and recipes
- `quick-reference.md` - Cheat sheet for functype APIs
For more examples and detailed documentation, visit:
- **GitHub**: https://github.com/jordanburke/functype
- **Docs**: https://jordanburke.github.io/functype/
Files in this package (4)
- SKILL.md 18 KB
- references/common-patterns.md 15 KB
- references/feature-matrix.md 1 KB
- references/quick-reference.md 33 KB
Versions
The database has no other skills named functype.
Database snapshot: 13.11.2026 · package version 8287a37414dd (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 95functype-developer
Assist contributors working on the functype library codebase. Use this skill when creating new data structures, implementing functional interfaces (Functor, Monad, Foldable), adding tests, debugging library internals, or understanding functype's Scala-inspired architecture… - 100language-ext
Use when applying comprehensive functional programming patterns in C# with language-ext, including Option, Either, Try, immutable collections, and monadic composition. USE FOR: Option<T> for null elimination, Either<L,R> for typed error handling, Try<T> for exception handling,… - 95ddd-ts-fp
ACTIVATE when modeling DDD aggregates, value objects and domain logic in TypeScript using functional patterns. ACTIVATE for 'aggregate', 'smart constructor', 'make*', 'validation pipeline', 'enrichment', 'domain handler' in TypeScript. Provides TypeScript-specific examples for… - 100effect-ts
Effect is a TypeScript library for typed errors, dependency injection, structured concurrency, retries, streams and schema validation. Use when someone asks to "handle errors without try-catch", "type-safe error handling in TypeScript", "dependency injection without classes",… - 100ts-functional
ACTIVATE when writing functional-style TypeScript: pipe, compose, currying, Result types, railway-oriented programming, or AsyncResult. ACTIVATE for 'pipe', 'Result type', 'railway', 'functional', 'chain'. Covers: type-safe pipe implementation, currying patterns, generic Result… - 95java-streams-api
Use when Java Streams API for functional-style data processing. Use when processing collections with streams.