惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
Martin Fowler
Martin Fowler
T
Threat Research - Cisco Blogs
Blog — PlanetScale
Blog — PlanetScale
S
Secure Thoughts
博客园 - 三生石上(FineUI控件)
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
K
Kaspersky official blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
H
Help Net Security
博客园 - 叶小钗
爱范儿
爱范儿
GbyAI
GbyAI
I
Intezer
M
MIT News - Artificial intelligence
Latest news
Latest news
Schneier on Security
Schneier on Security
T
Tor Project blog
Simon Willison's Weblog
Simon Willison's Weblog
I
InfoQ
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
C
CXSECURITY Database RSS Feed - CXSecurity.com
罗磊的独立博客
N
News and Events Feed by Topic
T
The Blog of Author Tim Ferriss
V2EX - 技术
V2EX - 技术
B
Blog
T
Tailwind CSS Blog
N
Netflix TechBlog - Medium
Security Latest
Security Latest
V
V2EX
F
Fortinet All Blogs
Forbes - Security
Forbes - Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
The Hacker News
The Hacker News
Scott Helme
Scott Helme
P
Privacy International News Feed
P
Palo Alto Networks Blog
H
Heimdal Security Blog
C
Cisco Blogs
T
The Exploit Database - CXSecurity.com
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
G
Google Developers Blog
W
WeLiveSecurity
L
LINUX DO - 最新话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Functional programming in TypeScript: the abstractions I actually use and the ones I dropped
Juan Torchia · 2026-06-18 · via DEV Community

Functional programming in TypeScript: the abstractions I actually use and the ones I dropped

There's a specific moment I recognize in almost every developer who arrives at TypeScript from a typed-language background: you open the fp-ts docs, you see pipe, Option, TaskEither, ReaderTaskEither, and you think "this is what I was missing." The type checker backs you up. The API is beautiful. The theory is solid.

Three weeks later, the PR has 800 lines of changes and a comment from a teammate that says: "what does fold do here?"

My thesis is this: functional patterns have real value in TypeScript, but full fp-ts adoption has an onboarding cost that almost nobody mentions when evangelizing the library. The criterion I ended up with — after evaluating full adoption and rejecting it — is: adopt the patterns, not the library, unless the entire team is aligned and willing to sustain it.

I'm not anti-FP. I use pipe, I have a homegrown Result type, and I think in pure functions when I can. But there's a difference between writing functional code and adopting a framework of mathematical categories in a collaborative project.


What fp-ts says and what it doesn't

fp-ts is a library by Giulio Canti that ports Haskell and Scala concepts to TypeScript with correct types: functors, monads, applicatives, the full trilogy. The documentation is rigorous. The types are precise. And if you come from Haskell, the API feels familiar almost immediately.

What the documentation doesn't say — because it's not its job to say it — is how much it costs to bring into a team where half the people never wrote Haskell, where PRs get reviewed under sprint pressure, and where onboarding a new dev has to be measured in days, not weeks of category theory.

fp-ts requires internalizing:

  • The algebraic type model (Either, Option, Task)
  • The difference between map, chain, and ap
  • How pipe composes functions with those types
  • Why TaskEither exists and what problem it solves vs. a Promise<Result<T, E>>

That's not a problem with the library. It's a trade-off that exists and is worth naming before you open a PR.


The three patterns that actually survived

1. pipe — composition without magic

pipe doesn't need fp-ts. TypeScript has Array.prototype and you can implement a minimal version in ten lines. The idea is simple: a series of transformations chained left to right, where each function receives the output of the previous one.

// minimal pipe — no external dependencies
function pipe<A>(value: A): A;
function pipe<A, B>(value: A, fn1: (a: A) => B): B;
function pipe<A, B, C>(value: A, fn1: (a: A) => B, fn2: (b: B) => C): C;
function pipe(value: unknown, ...fns: Array<(x: unknown) => unknown>): unknown {
  return fns.reduce((acc, fn) => fn(acc), value);
}

// Real usage: transform a database object before returning it
const toPublicUser = (raw: RawUserRow) =>
  pipe(
    raw,
    normalizeDates,       // Date → ISO string
    hideInternalFields,   // strip sensitive fields
    addMetadata           // attach computed fields
  );

Any dev understands this on first read. It doesn't require knowing what a monad is. The benefit is concrete: you eliminate intermediate variables like const step1 = ...; const step2 = ... and make the order of transformations explicit.

It survived because the adoption cost is nearly zero and the readability benefit is immediate.

2. Result<T, E> — explicit error handling without exceptions

This is the pattern that brought me the most value, and the one that's hardest for teams coming from a pure try/catch world.

The idea: instead of throwing exceptions, a function that can fail returns Result<T, E> — either a successful value (Ok) or a typed error (Err).

// Minimal definition — no fp-ts, no dependencies
type Ok<T> = { ok: true; value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E = Error> = Ok<T> | Err<E>;

// Constructors
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
const err = <E>(error: E): Err<E> => ({ ok: false, error });

// Usage in a Next.js Server Action
async function saveProfile(
  input: unknown
): Promise<Result<UserProfile, ValidationError | DatabaseError>> {
  const parsed = profileSchema.safeParse(input);
  if (!parsed.success) {
    return err({ type: "validation", issues: parsed.error.issues });
  }

  try {
    const user = await db.user.update({ where: { id: parsed.data.id }, data: parsed.data });
    return ok(user);
  } catch (e) {
    return err({ type: "database", cause: e });
  }
}

// In the caller — the type checker forces you to handle both cases
const result = await saveProfile(formData);
if (!result.ok) {
  // TypeScript knows result.error is ValidationError | DatabaseError
  return handleError(result.error);
}
// Here TypeScript knows result.value is UserProfile
return result.value;

Why not Either from fp-ts? Because Either<E, A> requires knowing the convention that the error goes on the left, understanding fold, mapLeft, chain. With a homegrown Result, any dev who's seen a Rust API or an ok/error pattern gets it in a minute.

The honest trade-off: you lose the ability to compose errors with chain elegantly. If you need to chain five operations that can fail, fp-ts TaskEither is more expressive. For the common case — a function that can fail with two error types — the homegrown type wins on zero friction.

3. Pure functions where state isn't needed

This isn't a library pattern. It's a design discipline.

When I write transformation, validation, or formatting helpers, I write them as pure functions: same input, same output, no side effects. The benefit is instant testability — no mocks, no setup.

// Pure function — testable without setup
function formatPrice(
  cents: number,
  options: { currency: string; locale: string }
): string {
  return new Intl.NumberFormat(options.locale, {
    style: "currency",
    currency: options.currency,
  }).format(cents / 100);
}

// Test with no mocks, no beforeEach, no dependencies
expect(formatPrice(1099, { currency: "ARS", locale: "es-AR" })).toBe("$ 10,99");

This doesn't require fp-ts. It requires the discipline to separate pure logic from effects (IO, database, system dates).


What I dropped and why

TaskEither for async/await

TaskEither<E, A> from fp-ts is a monad that combines Task (async operation) with Either (result that can fail). In theory, it's the perfect solution for async functions that can fail with typed errors.

In practice, on a project with Next.js Server Actions and Prisma, adding TaskEither meant rewriting the entire data access layer in a style the rest of the team didn't recognize. The type errors TypeScript gives you when you fail to compose TaskEither correctly are not friendly to someone who's never seen the library.

I ended up with Promise<Result<T, E>> — conceptually identical, but without the onboarding debt.

Option<A> as a replacement for null/undefined

Option (or Maybe) is the pattern for values that might not exist. The idea is that instead of string | null, you use Option<string> and operate with map, getOrElse, fold.

The problem in TypeScript 5.x with strictNullChecks enabled: string | null is already type-safe. The compiler forces you to do the check before using the value. Most of the team already handles null and undefined with optional chaining (?.) and nullish coalescing (??).

Adding Option<A> on top of that is an abstraction over an abstraction that TypeScript already solved. I didn't adopt it.

Reader/State monads for dependency injection

ReaderTaskEither is arguably the pinnacle of fp-ts for real applications: it combines injected dependencies (Reader), async state (Task), and typed errors (Either). The learning curve, without exaggerating, requires weeks for a dev coming from OOP.

Consider it if you have a team where everyone has a functional background and the project justifies it. On a mixed team, it's a liability, not an asset.


The decision matrix: when to adopt each pattern

Before adopting any functional abstraction, run it through these four criteria:

Pattern Team understands it in < 30 min? TypeScript solves it natively? Worth the cost?
pipe (homegrown) ✅ Yes Not native, but trivial ✅ Always
Result<T, E> homegrown ✅ Yes No (requires discipline) ✅ When you have typed errors
Pure functions ✅ Yes N/A ✅ Whenever you can
Option<A> from fp-ts ⚠️ 30-60 min ✅ Yes (`T \ null`)
TaskEither from fp-ts ❌ Days/weeks No ✅ Only if the team is FP-first
ReaderTaskEither ❌ Weeks No ⚠️ FP-first projects only

The practical rule: if the abstraction requires the team to read a category theory guide before doing a PR review, the adoption cost is real and it compounds.


What you can't conclude without your own data

This is where I have to be honest about the limits of this analysis:

  • I don't have team velocity numbers to back up "fp-ts slows onboarding by X%". It's a pattern reported across ecosystem discussions, but the magnitude depends on the specific team.
  • I can't claim that homegrown Result scales better than fp-ts Either in 100k-line projects without having measured it. For projects with complex error composition, fp-ts might be better.
  • The learning curve depends on the team's background. If everyone comes from Scala, fp-ts is natural. The analysis changes completely.

If you want your own data: take a small module, rewrite it with full fp-ts, bring in someone from the team who wasn't part of the rewrite, and measure how long it takes them to understand the PR without context. That gives you concrete information for the decision.


FAQ

Do I need fp-ts to write functional code in TypeScript?

No. pipe, Result, pure functions — all of these are patterns you can implement in 50 lines with zero dependencies. fp-ts is a library that formalizes them with stricter types and more powerful composition, but the patterns exist independently of the library.

Isn't Result<T, E> just reinventing the wheel?

It's reinventing a smaller wheel on purpose. Either<E, A> from fp-ts has more composition capability, but it carries the entire library API with it. If you don't need chain or sequenceArray, the homegrown type is enough and has near-zero adoption cost.

When would I adopt full fp-ts?

If the team has a functional background (Scala, Haskell, Elm), if the project has complex domain logic with many chained operations that can fail, and if onboarding new devs has room to include the theory. It's not a one-person decision — it requires team consensus.

Does strictNullChecks replace Option<A>?

For most cases, yes. TypeScript with strictNullChecks: true forces you to handle null and undefined before using them. Optional chaining (?.) and nullish coalescing (??) cover 90% of Option use cases. The remaining 10% — elegant composition of optional values in long pipelines — is where Option shines, but that case isn't the most common one.

Isn't pipe the same as chaining methods?

Conceptually similar, but with one important difference: pipe works with free functions, not object methods. That means you can compose transformations over any type without that type needing to have those methods. It's more composable and more independently testable.

Is it worth learning fp-ts even if I don't fully adopt it?

Yes, and this is what I value most from the whole exercise. Studying fp-ts made me think better about typed errors, about the separation between pure logic and effects, and about what "composable" actually means. I use those concepts every day even though I don't use the library. Learning and adopting are independent decisions.


My position and the concrete next step

I started wanting to write Haskell in TypeScript. I ended up with three things: a 15-line pipe, a 10-line Result<T, E>, and the discipline to separate pure functions from effects. Not glamorous. Maintainable, though.

fp-ts is a serious, well-designed library with an active community. If you're evaluating it, read the official documentation — especially the guides section — before deciding. What you'll find is powerful. The question is whether the whole team can sustain it.

My practical recommendation right now: if you're evaluating FP in TypeScript, start with the three patterns that survived. Implement them yourself in an afternoon — don't install anything. When those patterns feel insufficient for the complexity you have, that's when you evaluate fp-ts seriously, with the team, with a pilot module, and with clear acceptance criteria.

If you're interested in how explicit error handling connects to other levels of the stack, the post on Spring Boot Actuator and what to expose has a similar perspective: deciding deliberately what you surface and what you don't. And if you're working in a multi-service environment, OpenTelemetry in Next.js shows how the context you lose at the edge follows the same "leaky abstraction" pattern as poorly used monads.


Primary source:


This article was originally published on juanchi.dev