今日已更新 240 条资讯 | 累计 23823 条内容
关于我们

Understanding Monads in TypeScript: A Practical Guide

Adriel Avila 2026年07月23日 23:37 1 次阅读 来源:Dev.to

You have read five blog posts about monads. Each one started with category theory, mentioned burritos, and left you more confused than before. Let's skip all of that. Here is the short version: a monad is a container that supports three operations. You already use two monads every day in TypeScript — Promise and Array . Once you see the pattern, every monad in @oofp/core will feel familiar. The Three Operations Every monad has three things: of(a) — Put a value into the container. map(f) — Transform the value inside, keep the container shape. chain(f) — Transform the value into a new container, then flatten. That's it. If a type supports these three operations and follows a few simple laws, it's a monad. Let's see this with types you already know. Promise — a monad you use daily // of — wrap a value const p = Promise . resolve ( 42 ); // map — transform the inside (then with a plain return) const doubled = p . then (( x ) => x * 2 ); // Promise<number> // chain — transform into a new Promise (then with an async return) const fetched = p . then (( id ) => fetch ( `/api/users/ ${ id } ` )); // Promise<Response> Promise.resolve is of . .then acts as both map and chain — JavaScript conflates them. When your callback returns a plain value, it's map . When it returns a Promise , it's chain . The runtime flattens the nested Promise<Promise<T>> into Promise<T> automatically. Array — another monad hiding in plain sight // of — wrap a value const arr = [ 42 ]; // map — transform each element const doubled = arr . map (( x ) => x * 2 ); // [84] // chain — transform each element into an array, then flatten const expanded = arr . flatMap (( x ) => [ x , x * 10 ]); // [42, 420] Array.of (or just [value] ) is of . .map is map . .flatMap is chain . Same pattern, different container. The insight is: chain is map followed by flatten . That's why it's also called flatMap or bind . You apply a function that returns a new container, then flatten the nested result. Maybe: Eliminating null

本文内容来源于互联网,版权归原作者所有
查看原文