25 FP in TypeScript and Effect
Lesson goal See how the ideas of the course (composition with pipe, Maybe and Either, effects as values) look in TypeScript with Effect 4, learn to read the Effect<A, E, R> type and decide when moving to Effect pays off.
This lesson is a bridge from the course to production code. The running example from the "Functional programming" lesson (take the users who are online and older than 20 and get the name of the first one) is rewritten here in TypeScript with the Effect 4 library. The task and the answer stay the same (John), and step by step you can see what each layer adds: types, Option instead of Maybe, checking the incoming data, and errors in the type of the program.
The course is written in JavaScript because the ideas of functional programming do not depend on a type system, and in JS they are visible without extra syntax. In production they are often written in TypeScript: there a missing value and possible errors become part of the signature, and the compiler checks how the code handles them. The TypeScript examples in this lesson are for reading only, the playground does not run them. Both exercises at the end of the lesson are in plain JavaScript and run in the playground as usual.
How to read TypeScript
TypeScript is JavaScript with type annotations: the compiler checks them and strips them before running. An annotation is written after a colon: name: string is a string, age: number is a number. The union type 'online' | 'offline' allows only one of the listed values. The generic <A> is a type parameter, the same variable a from the "Hindley–Milner type notation" lesson, only capitalized: the signature head :: [a] -> Maybe a is written in TypeScript as <A>(self: ReadonlyArray<A>) => Option<A>. ReadonlyArray is an array that the function promises not to change.
import { Option } from 'effect'
// Union type: the status can only be one of the two strings
type Status = 'online' | 'offline'
// The shape of a user: field names and their types
interface User {
readonly name: string
readonly status: Status
readonly age: number
}
// Hindley–Milner: head :: [a] -> Maybe a
// TypeScript: <A>(self: ReadonlyArray<A>) => Option<A>
// <A> is a type parameter, the same variable a, only capitalized
// Option.Option<A> is the Option type from the Option module
const head = <A>(self: ReadonlyArray<A>): Option.Option<A> =>
self.length > 0 ? Option.some(self[0]) : Option.none()
const users: ReadonlyArray<User> = [
{ name: 'John', status: 'online', age: 25 },
]
console.log(Option.isSome(head(users))) // true
console.log(Option.isNone(head([]))) // true
// head(42) will not compile: a number is not an array
// { name: 'Bob', status: 'away', age: 30 } won't compile either:
// 'away' is not a Statuspipe and Option instead of S.pipe and Maybe
Now the pure part of the example. The pipe function from effect takes the value first and then the steps of the pipeline: pipe(x, f, g) does the same as S.pipe([f, g])(x) in Sanctuary. If there is no value yet and you need the pipeline function itself, flow(f, g) builds it. The Array module from effect provides filter and head, and head returns an Option, the counterpart of Maybe: Some with a value or None.
// Array from effect is renamed Arr so as not to shadow the built-in Array
import { Array as Arr, Option, pipe } from 'effect'
interface User {
readonly name: string
readonly status: 'online' | 'offline'
readonly age: number
}
const users: ReadonlyArray<User> = [
{ name: 'John', status: 'online', age: 25 },
{ name: 'Alex', status: 'offline', age: 18 },
{ name: 'Angel', status: 'online', age: 18 },
]
const isOnline = (user: User): boolean => user.status === 'online'
const olderThan = (age: number) => (user: User): boolean => user.age > age
// searchOnlineUser :: [User] -> String
const searchOnlineUser = (list: ReadonlyArray<User>): string =>
pipe(
list, // in effect's pipe the value comes first, not an array of functions
Arr.filter(isOnline), // only the users who are online
Arr.filter(olderThan(20)), // only those older than 20
Arr.head, // Option<User>: Some(user), or None for an empty list
Option.map((user) => user.name), // the name inside the Option
Option.getOrElse(() => ''), // take the name out, '' for None
)
console.log(searchOnlineUser(users)) // 'John'
console.log(searchOnlineUser([]) === '') // trueThe answer is the same: John. One difference is easy to miss: Option.getOrElse takes a function that returns the fallback, while S.fromMaybe takes the value itself. The rest maps almost one to one, as the table shows. In Effect 3 the Result module was called Either, with the variants Right and Left, so articles and examples written before version 4 use Either.
| Sanctuary | Effect 4 | Meaning |
|---|---|---|
| Maybe a | Option<A> | the value may be missing |
| Just (x), Nothing | Some and None: Option.some(x), Option.none() | there is a value or there is none |
| Either a b | Result<A, E> | a result or an error; Result lists the success type first, then the error type |
| Right (x), Left (e) | Success and Failure: Result.succeed(x), Result.fail(e) | a success or an error with a reason |
| S.map(f) | Option.map(f) | apply f to the value inside |
| S.chain(f) | Option.flatMap(f) | f returns an Option itself: apply it and remove the extra layer |
| S.fromMaybe(x) | Option.getOrElse(() => x) | take the value out with a fallback; in Effect the fallback is a function |
| S.either(f)(g) | Result.match({ onFailure: f, onSuccess: g }) | handle both cases at the exit |
| S.pipe([f, g])(x) | pipe(x, f, g) | a pipeline; in Effect the value comes first |
Effect<A, E, R>
In the "Currying and asynchrony (evolution)" lesson the requests were promises, and an error at any step ended up in a single catch. A promise starts working the moment it is created, and its type does not show what may end up in catch. Effect works differently: it is a lazy description of the work, a value that can be stored, passed around and assembled from parts. Nothing runs until the description is passed to Effect.runPromise or Effect.runSync. The Effect<A, E, R> type has three parameters: A is the type of the result, E is the errors that may happen, R is the services needed to run it. When there are no errors or services, their place is taken by never, a type with no values; omitted E and R are never as well, so Effect<string> is Effect<string, never, never>. A possible error is visible in the signature just as a possible missing value is visible in Maybe a.
Schema: checking data at the boundary
TypeScript types are checked only at compile time, while a server response arrives at run time, and the types will not check it. The comment in the example from the "Functional programming" lesson warned about this. Schema describes the data once, and that description gives both the type and a check at run time. Schema.decodeUnknownResult(schema) gives a checking function, and it returns a Result: Success with the checked data or Failure describing what is wrong.
import { Result, Schema } from 'effect'
// A schema describes the data once: it gives both the type and the check
const User = Schema.Struct({
name: Schema.String,
status: Schema.Literals(['online', 'offline']),
age: Schema.Number,
})
// The type is derived from the schema, no need to write an interface by hand
type User = typeof User.Type
const Users = Schema.Array(User)
// The check returns a Result: Success with the data or Failure with an error
const check = (data: unknown): string =>
Result.match(Schema.decodeUnknownResult(Users)(data), {
onSuccess: (users: ReadonlyArray<User>) => 'users: ' + users.length,
onFailure: () => 'data failed the check',
})
// Responses from the "server": in the second one the age came as a string
console.log(check([{ name: 'John', status: 'online', age: 25 }]))
// 'users: 1'
console.log(check([{ name: 'Alex', status: 'offline', age: '18' }]))
// 'data failed the check'The whole program
What remains is to assemble everything into one program. Effect.gen reads like async/await: yield* is written instead of await, and errors do not go to a shared catch but accumulate in the type. Tagged errors are declared with Data.TaggedError: the _tag field tells one error from another, and Effect.catchTag handles an error by its tag. In version 4 an Option is not an effect, so it is turned into one with Effect.fromOption, which also states the error that None becomes.
import { Array as Arr, Data, Effect, pipe, Schema } from 'effect'
const User = Schema.Struct({
name: Schema.String,
status: Schema.Literals(['online', 'offline']),
age: Schema.Number,
})
// Tagged errors: the _tag field tells one error from another
class FetchError extends Data.TaggedError('FetchError')<{
readonly reason: string
}> {}
class UserNotFound extends Data.TaggedError('UserNotFound')<{}> {}
// The "server": an effect that may fail with FetchError
// fetchAllUsers :: Effect<unknown, FetchError>
const fetchAllUsers = Effect.tryPromise({
try: (): Promise<unknown> => Promise.resolve([
{ name: 'John', status: 'online', age: 25 },
{ name: 'Alex', status: 'offline', age: 18 },
{ name: 'Angel', status: 'online', age: 18 },
]),
catch: (cause) => new FetchError({ reason: String(cause) }),
})
// Effect.gen reads like async/await: yield* instead of await
// program :: Effect<string, FetchError | SchemaError | UserNotFound>
const program = Effect.gen(function* () {
const data = yield* fetchAllUsers
const users = yield* Schema.decodeUnknownEffect(Schema.Array(User))(data)
const first = pipe(
users,
Arr.filter((user) => user.status === 'online' && user.age > 20),
Arr.head,
)
// Option is not an effect: turn it into an effect with its own error
const user = yield* Effect.fromOption(first, () => new UserNotFound())
return user.name
})
// Nothing has run yet: program is only a description of the work.
// Handled errors leave the type, at the end it is Effect<string, never>
const safe = program.pipe(
Effect.catchTag('UserNotFound', () => Effect.succeed('')),
Effect.catch(() => Effect.succeed('service unavailable')),
)
Effect.runPromise(safe).then(console.log) // 'John'The type of program says that it returns a string or ends with one of three errors: FetchError, SchemaError or UserNotFound. Effect.catchTag removes UserNotFound from the type, Effect.catch handles all the rest, and what is left is Effect<string, never>: the compiler knows there are no unhandled errors. Without the handlers the errors would stay in the type, and Effect.runPromise would return a rejected promise on an error.
The third parameter, R, is empty in the example. In real code dependencies go through it: a database, an HTTP client, configuration. A service is declared with Context, an implementation is provided with Layer, and Effect.runPromise accepts only an effect with R = never, so the compiler points out a forgotten dependency. In tests the same service is replaced with a different Layer. Concurrency, retries and timeouts are built into the library as well: Effect.all with the concurrency option, Effect.retry and Effect.timeout. These are topics for a separate discussion; here it is enough to know they exist.
Where Effect pays off
- Backends and integrations with several points of failure (the network, a database, queues): errors are visible in the type, and retries, timeouts and cancellation are built into the library.
- Long-lived code that many people change: the compiler points out unhandled errors and missing dependencies.
- External data: Schema gives both the type and the check from one description.
- Concurrent tasks where the number of parallel operations has to be limited and the operations can be cancelled.
- Tests in which services are replaced through Layer.
Where Effect does not pay off
- Scripts, prototypes and a simple CRUD front end: an error there is cheap, and learning the library is expensive.
- A team without TypeScript, without time to learn, or with frequent turnover: every newcomer has to learn the effect model.
- A client page where every kilobyte counts: measure the bundle size on your own project before deciding.
Versions, fp-ts and what's next
The examples are written for Effect 4: Effect 4.0.0 came out on October 1, 2026, and the 3.x line still receives fixes. The predecessor of Effect in TypeScript is the fp-ts library. The fp-ts project has announced that it is merging with the Effect ecosystem, and according to the fp-ts README, Effect can be regarded as the successor to fp-ts v2. The latest fp-ts release, 2.16.11, came out on August 18, 2025. For new code Effect is the sensible choice, while fp-ts stays where it is already in use. Versions and dates are given according to the npm registry as of October 2026.
Next comes the "How to choose an FP library" lesson: it compares Effect with Vanilla JS, Lodash, Ramda, Sanctuary and fp-ts by budget, project stage and team. The Effect documentation: effect.website.
Key points
- pipe from effect takes the value first and then the steps: pipe(x, f, g). Option with Some and None corresponds to Maybe, Result with Success and Failure to Either, and Option.getOrElse takes a function, not a value.
- Effect<A, E, R> is a lazy description of the work: A is the result, E the possible errors, R the required services. Nothing runs before Effect.runPromise or Effect.runSync.
- Tagged errors are declared with Data.TaggedError, and Effect.catchTag handles them by tag and removes them from the type. Effect.gen reads like async/await, only yield* is written instead of await.
- Schema describes the data once and gives both the type and a run-time check from that description: TypeScript types on their own do not check external data.
- Effect pays off where an error is costly: backends, integrations, long-lived code, external data. In scripts, prototypes and a simple front end the cost of learning it usually outweighs the benefit.
Exercises
Exercise 1
An effect is a description of the work, not the work itself. Repeat this idea in plain JavaScript, without libraries, using the names from Effect. sync(thunk) returns a description { run: thunk } and calls nothing. map(f)(effect) returns a new description: when run, it runs effect and applies f to the result. runSync(effect) runs a description and returns the result. The calls counter shows how many times the "request" has actually run. Compare with a promise: what does the counter show right after new Promise?
Starter code
let calls = 0
// fetchName :: () -> String, a "request" that counts its calls
const fetchName = () => {
calls += 1
return 'John'
}
// sync :: (() -> a) -> Effect a
// map :: (a -> b) -> Effect a -> Effect b
// runSync :: Effect a -> a
// your code
const program = map((name) => name.toUpperCase())(sync(fetchName))
console.log(`after building: ${calls}`)
console.log(runSync(program))
console.log(runSync(program))
console.log(`after two runs: ${calls}`)
new Promise((resolve) => resolve(fetchName()))
console.log(`right after new Promise: ${calls}`)Expected output
after building: 0 JOHN JOHN after two runs: 2 right after new Promise: 3
Show solution
let calls = 0
// fetchName :: () -> String, a "request" that counts its calls
const fetchName = () => {
calls += 1
return 'John'
}
// sync :: (() -> a) -> Effect a
// a description is an object with a run function that nobody has called yet
const sync = (thunk) => ({ run: thunk })
// map :: (a -> b) -> Effect a -> Effect b
// a new description: when run, it runs effect and applies f; right now it does nothing
const map = (f) => (effect) => ({ run: () => f(effect.run()) })
// runSync :: Effect a -> a
// the only place where the work is done
const runSync = (effect) => effect.run()
const program = map((name) => name.toUpperCase())(sync(fetchName))
console.log(`after building: ${calls}`)
console.log(runSync(program))
console.log(runSync(program))
console.log(`after two runs: ${calls}`)
// a promise starts working the moment it is created, with no run at all
new Promise((resolve) => resolve(fetchName()))
console.log(`right after new Promise: ${calls}`)Exercise 2
Tagged errors without a library. A result is an object { _tag: 'Success', value } or { _tag: 'Failure', error }, and every error has a _tag field too. Write findOnline(id): if there is no user with that id, return a Failure with the error { _tag: 'UserNotFound', id }; if the user is offline, a Failure with { _tag: 'UserOffline', id }; otherwise a Success with the user's name. Then write catchTag(tag, handler): a function of a result that turns a Failure with an error of that tag into a Success with the value handler(error) and returns any other result unchanged. This is how Effect.catchTag works: the handled error disappears, the others pass through. In Effect, though, the handler returns an effect, for example Effect.succeed('guest'); here it returns the value itself for simplicity.
Starter code
const succeed = (value) => ({ _tag: 'Success', value })
const fail = (error) => ({ _tag: 'Failure', error })
const users = [
{ id: 1, name: 'John', status: 'online' },
{ id: 2, name: 'Alex', status: 'offline' },
]
// show :: Result -> String, matching on the _tag of the result and of the error
const show = (result) =>
result._tag === 'Success' ? `Success (${result.value})` : `Failure (${result.error._tag})`
// findOnline :: Number -> Result
// catchTag(tag, handler) :: Result -> Result
// your code
const ids = [1, 2, 3]
ids.forEach((id) => {
const result = catchTag('UserNotFound', () => 'guest')(findOnline(id))
console.log(`${id}: ${show(result)}`)
})Expected output
1: Success (John) 2: Failure (UserOffline) 3: Success (guest)
Show solution
const succeed = (value) => ({ _tag: 'Success', value })
const fail = (error) => ({ _tag: 'Failure', error })
const users = [
{ id: 1, name: 'John', status: 'online' },
{ id: 2, name: 'Alex', status: 'offline' },
]
// show :: Result -> String, matching on the _tag of the result and of the error
const show = (result) =>
result._tag === 'Success' ? `Success (${result.value})` : `Failure (${result.error._tag})`
// findOnline :: Number -> Result
const findOnline = (id) => {
const user = users.find((u) => u.id === id)
if (user === undefined) return fail({ _tag: 'UserNotFound', id })
if (user.status !== 'online') return fail({ _tag: 'UserOffline', id })
return succeed(user.name)
}
// catchTag(tag, handler) :: Result -> Result
// an error with this tag becomes a Success, everything else passes unchanged
const catchTag = (tag, handler) => (result) =>
result._tag === 'Failure' && result.error._tag === tag ? succeed(handler(result.error)) : result
const ids = [1, 2, 3]
ids.forEach((id) => {
const result = catchTag('UserNotFound', () => 'guest')(findOnline(id))
console.log(`${id}: ${show(result)}`)
})
// nobody handled UserOffline: the error stayed in the result,
// just as in Effect it would stay in the E typePlayground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.