DEV Community

Cover image for Functional programming in TypeScript: the abstractions I actually use and the ones I dropped
Juan Torchia
Juan Torchia Subscriber

Posted on • Originally published at juanchi.dev

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

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
  );
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)