Scan your whole stack
Are you using functype?
Find out what’s in your code.
Scan your apps free in minutes (opens in a new tab)Latest version: v2.2.0
functype was last scanned on 24 Nov 2026 at version 2.2.0. Risk score 0 of 100. No malicious behavior was detected.
| Version | Published | Status |
|---|---|---|
| 2.2.0 LATEST | 24 Nov 2026 | No rules fired |
| 2.1.0 | 23 Nov 2026 | No rules fired |
| 2.0.0 | 22 Nov 2026 | No rules fired |
| 1.27.2 | 22 Nov 2026 | Not shown |
| 1.27.1 | 20 Nov 2026 | Not shown |
Findings for v2.2.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.
The score describes 2.2.0; other versions have their own rules, not their own score.
The publisher’s own README, as collected from the registry.
Functype is a lightweight functional programming library for TypeScript, drawing inspiration from functional programming paradigms, the Scala Standard Library, and ZIO. It provides a comprehensive set of utilities and abstractions designed to facilitate functional programming within TypeScript applications.
API Documentation · Cheatsheet for Scala / cats / fp-ts users
Get LLM-optimized API reference directly in your terminal:
npx functype # Overview of all types
npx functype Option # Detailed info for Option type
npx functype interfaces # All interface definitions
npx functype --json # JSON output for programmatic use
no-container-mutation reports a write through a cast. Under NODE_ENV=development collections also freeze each value, so a write from untyped code throws; FUNCTYPE_FREEZE=1 turns that on anywhere, such as a test suite, and FUNCTYPE_FREEZE=0 turns it off. Production doesn't freeze, because freezing was most of what building a collection costSome and None typesLeft and Rightfunctype is a small, dependency-free library of functional data types you adopt incrementally. Effect is a comprehensive effect system and runtime you build your application around. Both bring FP to TypeScript and overlap on the surface (an effect type, typed errors, DI), but they solve different problems. If you know Scala: functype is to Effect roughly what the standard library / cats-core is to ZIO.
Option, Either, Try, List, do-notation — with zero runtime dependencies, adoptable one function at a time (a List or Option is just a value you can delete from a single file). It includes a lightweight ZIO-shaped IO with typed errors and DI, but no runtime to build your app around.functype deliberately is not a framework — no fiber runtime, no structured concurrency, no Clock/Random. What it adds instead is an LLM-native loop no other FP library has: lint rules that enforce idioms (eslint-plugin-functype), a scorer/benchmark that measures adherence (functype-eval), and an MCP server + skill that teach models the API.
Full comparison, non-goals, and "choose Effect when…": docs/vs-effect.md.
Upgrading from 1.x? functype.org/upgrading-to-2 lists what to change.
# NPM
npm install functype
# Yarn
yarn add functype
# PNPM
pnpm add functype
# Bun
bun add functype
dist has one file per module, so a bundler keeps only what you use. An Option-only program ships 5.7 KB gzipped; one using IO.gen, Either, Option and List ships 11.5 KB. Root and subpath imports bundle the same:
import { Option } from "functype/option" // bundles the same as importing from "functype"
import { Either, IO, List, Option } from "functype/core" // the 17 names most code needs, in one import
For the measured sizes and how they are checked, see the Bundle Size guide.
{@includeCode test/docs/documentation-examples.spec.ts#readme-option-basic}
{@includeCode test/docs/documentation-examples.spec.ts#readme-either-basic}
import { List } from "functype"
const numbers = List([1, 2, 3, 4])
// Transform
const doubled = numbers.map((x) => x * 2) // List([2, 4, 6, 8])
// Filter
const evens = numbers.filter((x) => x % 2 === 0) // List([2, 4])
// Reduce
const sum = numbers.foldLeft(0)((acc, x) => acc + x) // 10
// Add/remove elements (immutably)
const withFive = numbers.add(5) // List([1, 2, 3, 4, 5])
const without3 = numbers.remove(3) // List([1, 2, 4])
// Universal container operations
const hasEven = numbers.exists((x) => x % 2 === 0) // true
const firstEven = numbers.find((x) => x % 2 === 0) // Some(2)
const evenCount = numbers.count((x) => x % 2 === 0) // 2
import { Try } from "functype"
// Safely execute code that might throw
const result = Try(() => {
// Potentially throwing operation
return JSON.parse('{"name": "John"}')
})
// Handle success/failure
if (result.isSuccess()) {
console.log("Result:", result.get())
} else {
console.error("Error:", result.error)
}
// Transform with map (only applies on Success)
const name = result.map((obj) => obj.name)
// Convert to Either
const either = result.toEither()
import { Lazy } from "functype"
// Create lazy computations
const expensive = Lazy(() => {
console.log("Computing...")
return Math.random() * 1000
})
// Value is computed on first access and memoized
const value1 = expensive.get() // Logs "Computing...", returns number
const value2 = expensive.get() // Returns same number, no log
// Transform lazy values
const doubled = expensive.map((x) => x * 2)
const formatted = doubled.map((x) => `Value: ${x}`)
// Chain computations
const result = Lazy(() => 10)
.flatMap((x) => Lazy(() => x + 5))
.map((x) => x * 2)
.get() // 30
Functype provides generator-based Do-notation for monadic composition, similar to Scala's for-comprehensions, with significant performance advantages for List operations:
import { Do, DoAsync, $ } from "functype"
import { Option, Right, Left, List, Try } from "functype"
// Chain multiple Option operations
const result = Do(function* () {
const x = yield* $(Option(5)) // Extract value from Option
const y = yield* $(Option(10)) // Extract value from another Option
const z = x + y // Regular computation
return z * 2 // Return final result
})
// result: Option<number> with value 30
// Mix different monad types (with Reshapeable)
const mixed = Do(function* () {
const a = yield* $(Option(5)) // From Option
const b = yield* $(Right<string, number>(10)) // From Either
const c = yield* $(List([15])) // From List
const d = yield* $(Try(() => 20)) // From Try
return a + b + c + d
})
// Convert result to desired type
const asOption = mixed.toOption() // Option<number> with value 50
// Error propagation - short-circuits on failure
const validation = Do(function* () {
const email = yield* $(validateEmail("user@example.com")) // Returns Option
const user = yield* $(fetchUser(email)) // Returns Either
const profile = yield* $(loadProfile(user.id)) // Returns Try
return profile
})
// If any step fails, the entire computation short-circuits
// List comprehensions - up to 12x FASTER than traditional flatMap!
const pairs = Do(function* () {
const x = yield* $(List([1, 2, 3]))
const y = yield* $(List([10, 20]))
return { x, y, product: x * y }
})
// pairs: List with 6 elements (all combinations)
// Performance comparison:
// Traditional: list.flatMap(x => list.flatMap(y => List([{x, y}]))) - slower
// Do-notation: 2.5x to 12x faster for cartesian products!
// Async operations with DoAsync
const asyncResult = await DoAsync(async function* () {
const user = yield* $(await fetchUserAsync(userId)) // Async Option
const score = yield* $(await getScoreAsync(user.id)) // Async Either
const bonus = yield* $(await calculateBonus(score)) // Async Try
return score + bonus
})
Performance Advantages:
When to Use Do-notation:
✅ Best for:
⚠️ Consider alternatives for:
Key Differences from Scala:
yield* $(monad) instead of x <- monadIO<R, E, A> is a lazy effect: nothing runs until you call a run method. E is the typed error and R the services it needs. functype 2.0 deleted Task, and IO replaces it.
import { IO } from "functype"
type User = { id: string; name: string; settings: string }
const loadUser = (id: string) =>
IO.tryPromise({
// the run's signal reaches fetch, so cancelling stops the request
try: (signal) => fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<User>),
catch: (error) => new Error(`Failed to load ${id}: ${String(error)}`),
})
// Nothing has run yet. run() gives an Either<Error, User>
const user = await loadUser("42").retry(2).timeout(5000).run()
// Cancel with a handle, or with your own AbortSignal
const { result, cancel } = loadUser("42").runCancellable()
const controller = new AbortController()
const exit = await loadUser("42").runExit({ signal: controller.signal }) // Success | Failure | Die | Interrupted
// A callback that may throw: in map a throw is a defect and run() rejects; mapTry makes it a typed error
const settings = loadUser("42").mapTry(
(user) => JSON.parse(user.settings) as unknown,
(error) => new Error(`Bad settings: ${String(error)}`),
)
withSpan(name, attributes?) runs an effect in a span, and a withSpan inside it nests under it without being passed a parent. functype ships only the contract, SpanTracer: with no tracer provided, withSpan does nothing. A tracer has three methods. start(name, attributes, parent) opens a span, run(span, fn) runs the body with the span active, and end(span, exit) closes it once, for every outcome.
import { context, type Span, SpanStatusCode, trace } from "@opentelemetry/api" // your dependency, not functype's
import { SpanTracer } from "functype"
const otel = trace.getTracer("my-app")
const otelTracer: SpanTracer<Span> = {
start: (name, attributes, parent) =>
otel.startSpan(name, { attributes }, parent ? trace.setSpan(context.active(), parent) : context.active()),
run: (span, fn) => context.with(trace.setSpan(context.active(), span), fn), // makes the span active
end: (span, exit) => {
if (exit._tag === "Failure" || exit._tag === "Die") span.setStatus({ code: SpanStatusCode.ERROR })
span.end()
},
}
// Provide the tracer outside the spans
await loadUser("42").withSpan("loadUser", { "user.id": "42" }).provideService(SpanTracer, otelTracer).run()
This bridge is a sketch, not a package: functype has no OpenTelemetry dependency. Because run makes the span active, a log sink inside withSpan reads the trace IDs with trace.getActiveSpan(). That needs a registered OpenTelemetry context manager, which the Node SDK sets up; without one, context.with runs the body with no span active. The IO docs cover nesting, cancellation and runSync.
import { Brand, ValidatedBrand } from "functype/branded"
// Create branded types for stronger type safety
type UserId = Brand<"UserId", string>
type Email = Brand<"Email", string>
// Simple branding - branded values ARE primitives!
const userId = Brand("UserId", "U123456")
console.log(userId) // "U123456" - it IS a string
console.log(typeof userId) // "string"
console.log(userId.toUpperCase()) // "U123456" - string methods work!
// Runtime-validated branding for safer input handling
const EmailValidator = ValidatedBrand("Email", (s: string) => /^[^@]+@[^@]+\.[^@]+$/.test(s))
const UserIdValidator = ValidatedBrand("UserId", (s: string) => /^U\d{6}$/.test(s))
// Safe creation with Option/Either return types
const email = EmailValidator.of("user@example.com") // Some(Brand<"Email", string>)
const invalidEmail = EmailValidator.of("invalid") // None
const userResult = UserIdValidator.from("U123456") // Right(Brand<"UserId", string>)
const userError = UserIdValidator.from("invalid") // Left("Invalid UserId: validation failed")
// Type safety in action
function getUserByEmail(email: Email): User {
/* ... */
}
// These calls are type-safe
const userId = UserId("U123456")
const email = Email("user@example.com")
const user = getUserByEmail(email) // Works
// These would be type errors
getUserByEmail("invalid") // Type error: Argument of type 'string' is not assignable to parameter of type 'Email'
getUserByEmail(userId) // Type error: Argument of type 'UserId' is not assignable to parameter of type 'Email'
Wire<T> marks a value in its serialization-safe shape: a DB row, an HTTP body, a JSONB payload. Zero runtime, assignable both ways with T, and the ESLint plugin's prefer-option / prefer-list skip everything inside it.
import type { Wire } from "functype"
type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArray<string> }>
type UserRows = Wire<ReadonlyArray<UserRow>>
// Convert inside the pipeline
const reachable = List(rows).filter((u) => Option(u.email).isSome())
Opt-in wrapper that emits one structured event per Option combinator to an injected Tracer:
import { TracedOption, type Tracer, type TraceEvent } from "functype"
const events: TraceEvent[] = []
const tracer: Tracer = { emit: (e) => void events.push(e) }
TracedOption(user, tracer, "span-1")
.map((u) => u.name.trim(), "trim")
.getOrElse(() => "anonymous", "fallback")
Functype provides Cond and Match for functional conditional logic without early returns:
Find threats in your stack.
OX Radar can check high-priority threats, like critical package CVEs, against your context.
Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.
The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).
The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.