[{"data":1,"prerenderedAt":206},["ShallowReactive",2],{"course-en-fp-in-typescript-and-effect":3},{"lesson":4,"number":197,"prev":198,"next":202},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":167,"exercises":178},"fp-in-typescript-and-effect",{"ru":7,"en":8},"","FP in TypeScript and Effect",{"ru":7,"en":10},"From JavaScript to TypeScript and Effect 4: pipe and Option instead of Maybe, Result instead of Either, typed errors, Schema, and where Effect pays off.",{"ru":7,"en":12},"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\u003CA, E, R> type and decide when moving to Effect pays off.",[14,17,19,22,24,29,31,33,36,38,113,115,117,119,121,124,126,128,131,133,135,137,151,153,161,163,165],{"type":15,"ru":7,"en":16},"text","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.",{"type":15,"ru":7,"en":18},"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.",{"type":20,"ru":7,"en":21},"heading","How to read TypeScript",{"type":15,"ru":7,"en":23},"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 \u003CA> 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 \u003CA>(self: ReadonlyArray\u003CA>) => Option\u003CA>. ReadonlyArray is an array that the function promises not to change.",{"type":25,"lang":26,"code":27},"code","ts",{"ru":7,"en":28},"import { Option } from 'effect'\n\n\u002F\u002F Union type: the status can only be one of the two strings\ntype Status = 'online' | 'offline'\n\n\u002F\u002F The shape of a user: field names and their types\ninterface User {\n  readonly name: string\n  readonly status: Status\n  readonly age: number\n}\n\n\u002F\u002F Hindley–Milner: head :: [a] -> Maybe a\n\u002F\u002F TypeScript:     \u003CA>(self: ReadonlyArray\u003CA>) => Option\u003CA>\n\u002F\u002F \u003CA> is a type parameter, the same variable a, only capitalized\n\u002F\u002F Option.Option\u003CA> is the Option type from the Option module\nconst head = \u003CA>(self: ReadonlyArray\u003CA>): Option.Option\u003CA> =>\n  self.length > 0 ? Option.some(self[0]) : Option.none()\n\nconst users: ReadonlyArray\u003CUser> = [\n  { name: 'John', status: 'online', age: 25 },\n]\n\nconsole.log(Option.isSome(head(users))) \u002F\u002F true\nconsole.log(Option.isNone(head([]))) \u002F\u002F true\n\n\u002F\u002F head(42) will not compile: a number is not an array\n\u002F\u002F { name: 'Bob', status: 'away', age: 30 } won't compile either:\n\u002F\u002F 'away' is not a Status",{"type":20,"ru":7,"en":30},"pipe and Option instead of S.pipe and Maybe",{"type":15,"ru":7,"en":32},"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.",{"type":25,"lang":26,"code":34},{"ru":7,"en":35},"\u002F\u002F Array from effect is renamed Arr so as not to shadow the built-in Array\nimport { Array as Arr, Option, pipe } from 'effect'\n\ninterface User {\n  readonly name: string\n  readonly status: 'online' | 'offline'\n  readonly age: number\n}\n\nconst users: ReadonlyArray\u003CUser> = [\n  { name: 'John', status: 'online', age: 25 },\n  { name: 'Alex', status: 'offline', age: 18 },\n  { name: 'Angel', status: 'online', age: 18 },\n]\n\nconst isOnline = (user: User): boolean => user.status === 'online'\nconst olderThan = (age: number) => (user: User): boolean => user.age > age\n\n\u002F\u002F searchOnlineUser :: [User] -> String\nconst searchOnlineUser = (list: ReadonlyArray\u003CUser>): string =>\n  pipe(\n    list, \u002F\u002F in effect's pipe the value comes first, not an array of functions\n    Arr.filter(isOnline), \u002F\u002F only the users who are online\n    Arr.filter(olderThan(20)), \u002F\u002F only those older than 20\n    Arr.head, \u002F\u002F Option\u003CUser>: Some(user), or None for an empty list\n    Option.map((user) => user.name), \u002F\u002F the name inside the Option\n    Option.getOrElse(() => ''), \u002F\u002F take the name out, '' for None\n  )\n\nconsole.log(searchOnlineUser(users)) \u002F\u002F 'John'\nconsole.log(searchOnlineUser([]) === '') \u002F\u002F true",{"type":15,"ru":7,"en":37},"The 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.",{"type":39,"caption":40,"columns":42,"rows":49},"table",{"ru":7,"en":41},"Sanctuary and Effect 4: what maps to what",[43,45,47],{"ru":7,"en":44},"Sanctuary",{"ru":7,"en":46},"Effect 4",{"ru":7,"en":48},"Meaning",[50,57,64,71,78,85,92,99,106],[51,53,55],{"ru":7,"en":52},"Maybe a",{"ru":7,"en":54},"Option\u003CA>",{"ru":7,"en":56},"the value may be missing",[58,60,62],{"ru":7,"en":59},"Just (x), Nothing",{"ru":7,"en":61},"Some and None: Option.some(x), Option.none()",{"ru":7,"en":63},"there is a value or there is none",[65,67,69],{"ru":7,"en":66},"Either a b",{"ru":7,"en":68},"Result\u003CA, E>",{"ru":7,"en":70},"a result or an error; Result lists the success type first, then the error type",[72,74,76],{"ru":7,"en":73},"Right (x), Left (e)",{"ru":7,"en":75},"Success and Failure: Result.succeed(x), Result.fail(e)",{"ru":7,"en":77},"a success or an error with a reason",[79,81,83],{"ru":7,"en":80},"S.map(f)",{"ru":7,"en":82},"Option.map(f)",{"ru":7,"en":84},"apply f to the value inside",[86,88,90],{"ru":7,"en":87},"S.chain(f)",{"ru":7,"en":89},"Option.flatMap(f)",{"ru":7,"en":91},"f returns an Option itself: apply it and remove the extra layer",[93,95,97],{"ru":7,"en":94},"S.fromMaybe(x)",{"ru":7,"en":96},"Option.getOrElse(() => x)",{"ru":7,"en":98},"take the value out with a fallback; in Effect the fallback is a function",[100,102,104],{"ru":7,"en":101},"S.either(f)(g)",{"ru":7,"en":103},"Result.match({ onFailure: f, onSuccess: g })",{"ru":7,"en":105},"handle both cases at the exit",[107,109,111],{"ru":7,"en":108},"S.pipe([f, g])(x)",{"ru":7,"en":110},"pipe(x, f, g)",{"ru":7,"en":112},"a pipeline; in Effect the value comes first",{"type":20,"ru":7,"en":114},"Effect\u003CA, E, R>",{"type":15,"ru":7,"en":116},"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\u003CA, 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\u003Cstring> is Effect\u003Cstring, never, never>. A possible error is visible in the signature just as a possible missing value is visible in Maybe a.",{"type":20,"ru":7,"en":118},"Schema: checking data at the boundary",{"type":15,"ru":7,"en":120},"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.",{"type":25,"lang":26,"code":122},{"ru":7,"en":123},"import { Result, Schema } from 'effect'\n\n\u002F\u002F A schema describes the data once: it gives both the type and the check\nconst User = Schema.Struct({\n  name: Schema.String,\n  status: Schema.Literals(['online', 'offline']),\n  age: Schema.Number,\n})\n\n\u002F\u002F The type is derived from the schema, no need to write an interface by hand\ntype User = typeof User.Type\n\nconst Users = Schema.Array(User)\n\n\u002F\u002F The check returns a Result: Success with the data or Failure with an error\nconst check = (data: unknown): string =>\n  Result.match(Schema.decodeUnknownResult(Users)(data), {\n    onSuccess: (users: ReadonlyArray\u003CUser>) => 'users: ' + users.length,\n    onFailure: () => 'data failed the check',\n  })\n\n\u002F\u002F Responses from the \"server\": in the second one the age came as a string\nconsole.log(check([{ name: 'John', status: 'online', age: 25 }]))\n\u002F\u002F 'users: 1'\nconsole.log(check([{ name: 'Alex', status: 'offline', age: '18' }]))\n\u002F\u002F 'data failed the check'",{"type":20,"ru":7,"en":125},"The whole program",{"type":15,"ru":7,"en":127},"What remains is to assemble everything into one program. Effect.gen reads like async\u002Fawait: 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.",{"type":25,"lang":26,"code":129},{"ru":7,"en":130},"import { Array as Arr, Data, Effect, pipe, Schema } from 'effect'\n\nconst User = Schema.Struct({\n  name: Schema.String,\n  status: Schema.Literals(['online', 'offline']),\n  age: Schema.Number,\n})\n\n\u002F\u002F Tagged errors: the _tag field tells one error from another\nclass FetchError extends Data.TaggedError('FetchError')\u003C{\n  readonly reason: string\n}> {}\nclass UserNotFound extends Data.TaggedError('UserNotFound')\u003C{}> {}\n\n\u002F\u002F The \"server\": an effect that may fail with FetchError\n\u002F\u002F fetchAllUsers :: Effect\u003Cunknown, FetchError>\nconst fetchAllUsers = Effect.tryPromise({\n  try: (): Promise\u003Cunknown> => Promise.resolve([\n    { name: 'John', status: 'online', age: 25 },\n    { name: 'Alex', status: 'offline', age: 18 },\n    { name: 'Angel', status: 'online', age: 18 },\n  ]),\n  catch: (cause) => new FetchError({ reason: String(cause) }),\n})\n\n\u002F\u002F Effect.gen reads like async\u002Fawait: yield* instead of await\n\u002F\u002F program :: Effect\u003Cstring, FetchError | SchemaError | UserNotFound>\nconst program = Effect.gen(function* () {\n  const data = yield* fetchAllUsers\n  const users = yield* Schema.decodeUnknownEffect(Schema.Array(User))(data)\n  const first = pipe(\n    users,\n    Arr.filter((user) => user.status === 'online' && user.age > 20),\n    Arr.head,\n  )\n  \u002F\u002F Option is not an effect: turn it into an effect with its own error\n  const user = yield* Effect.fromOption(first, () => new UserNotFound())\n  return user.name\n})\n\n\u002F\u002F Nothing has run yet: program is only a description of the work.\n\u002F\u002F Handled errors leave the type, at the end it is Effect\u003Cstring, never>\nconst safe = program.pipe(\n  Effect.catchTag('UserNotFound', () => Effect.succeed('')),\n  Effect.catch(() => Effect.succeed('service unavailable')),\n)\n\nEffect.runPromise(safe).then(console.log) \u002F\u002F 'John'",{"type":15,"ru":7,"en":132},"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\u003Cstring, 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.",{"type":15,"ru":7,"en":134},"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.",{"type":20,"ru":7,"en":136},"Where Effect pays off",{"type":138,"ordered":139,"items":140},"list",false,[141,143,145,147,149],{"ru":7,"en":142},"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.",{"ru":7,"en":144},"Long-lived code that many people change: the compiler points out unhandled errors and missing dependencies.",{"ru":7,"en":146},"External data: Schema gives both the type and the check from one description.",{"ru":7,"en":148},"Concurrent tasks where the number of parallel operations has to be limited and the operations can be cancelled.",{"ru":7,"en":150},"Tests in which services are replaced through Layer.",{"type":20,"ru":7,"en":152},"Where Effect does not pay off",{"type":138,"ordered":139,"items":154},[155,157,159],{"ru":7,"en":156},"Scripts, prototypes and a simple CRUD front end: an error there is cheap, and learning the library is expensive.",{"ru":7,"en":158},"A team without TypeScript, without time to learn, or with frequent turnover: every newcomer has to learn the effect model.",{"ru":7,"en":160},"A client page where every kilobyte counts: measure the bundle size on your own project before deciding.",{"type":20,"ru":7,"en":162},"Versions, fp-ts and what's next",{"type":15,"ru":7,"en":164},"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.",{"type":15,"ru":7,"en":166},"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.",[168,170,172,174,176],{"ru":7,"en":169},"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.",{"ru":7,"en":171},"Effect\u003CA, 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.",{"ru":7,"en":173},"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\u002Fawait, only yield* is written instead of await.",{"ru":7,"en":175},"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.",{"ru":7,"en":177},"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.",[179,188],{"task":180,"starter":182,"solution":184,"expected":186},{"ru":7,"en":181},"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?",{"ru":7,"en":183},"let calls = 0\n\n\u002F\u002F fetchName :: () -> String, a \"request\" that counts its calls\nconst fetchName = () => {\n  calls += 1\n  return 'John'\n}\n\n\u002F\u002F sync :: (() -> a) -> Effect a\n\u002F\u002F map :: (a -> b) -> Effect a -> Effect b\n\u002F\u002F runSync :: Effect a -> a\n\u002F\u002F your code\n\nconst program = map((name) => name.toUpperCase())(sync(fetchName))\nconsole.log(`after building: ${calls}`)\nconsole.log(runSync(program))\nconsole.log(runSync(program))\nconsole.log(`after two runs: ${calls}`)\n\nnew Promise((resolve) => resolve(fetchName()))\nconsole.log(`right after new Promise: ${calls}`)",{"ru":7,"en":185},"let calls = 0\n\n\u002F\u002F fetchName :: () -> String, a \"request\" that counts its calls\nconst fetchName = () => {\n  calls += 1\n  return 'John'\n}\n\n\u002F\u002F sync :: (() -> a) -> Effect a\n\u002F\u002F a description is an object with a run function that nobody has called yet\nconst sync = (thunk) => ({ run: thunk })\n\n\u002F\u002F map :: (a -> b) -> Effect a -> Effect b\n\u002F\u002F a new description: when run, it runs effect and applies f; right now it does nothing\nconst map = (f) => (effect) => ({ run: () => f(effect.run()) })\n\n\u002F\u002F runSync :: Effect a -> a\n\u002F\u002F the only place where the work is done\nconst runSync = (effect) => effect.run()\n\nconst program = map((name) => name.toUpperCase())(sync(fetchName))\nconsole.log(`after building: ${calls}`)\nconsole.log(runSync(program))\nconsole.log(runSync(program))\nconsole.log(`after two runs: ${calls}`)\n\n\u002F\u002F a promise starts working the moment it is created, with no run at all\nnew Promise((resolve) => resolve(fetchName()))\nconsole.log(`right after new Promise: ${calls}`)",{"ru":7,"en":187},"after building: 0\nJOHN\nJOHN\nafter two runs: 2\nright after new Promise: 3",{"task":189,"starter":191,"solution":193,"expected":195},{"ru":7,"en":190},"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.",{"ru":7,"en":192},"const succeed = (value) => ({ _tag: 'Success', value })\nconst fail = (error) => ({ _tag: 'Failure', error })\n\nconst users = [\n  { id: 1, name: 'John', status: 'online' },\n  { id: 2, name: 'Alex', status: 'offline' },\n]\n\n\u002F\u002F show :: Result -> String, matching on the _tag of the result and of the error\nconst show = (result) =>\n  result._tag === 'Success' ? `Success (${result.value})` : `Failure (${result.error._tag})`\n\n\u002F\u002F findOnline :: Number -> Result\n\u002F\u002F catchTag(tag, handler) :: Result -> Result\n\u002F\u002F your code\n\nconst ids = [1, 2, 3]\nids.forEach((id) => {\n  const result = catchTag('UserNotFound', () => 'guest')(findOnline(id))\n  console.log(`${id}: ${show(result)}`)\n})",{"ru":7,"en":194},"const succeed = (value) => ({ _tag: 'Success', value })\nconst fail = (error) => ({ _tag: 'Failure', error })\n\nconst users = [\n  { id: 1, name: 'John', status: 'online' },\n  { id: 2, name: 'Alex', status: 'offline' },\n]\n\n\u002F\u002F show :: Result -> String, matching on the _tag of the result and of the error\nconst show = (result) =>\n  result._tag === 'Success' ? `Success (${result.value})` : `Failure (${result.error._tag})`\n\n\u002F\u002F findOnline :: Number -> Result\nconst findOnline = (id) => {\n  const user = users.find((u) => u.id === id)\n  if (user === undefined) return fail({ _tag: 'UserNotFound', id })\n  if (user.status !== 'online') return fail({ _tag: 'UserOffline', id })\n  return succeed(user.name)\n}\n\n\u002F\u002F catchTag(tag, handler) :: Result -> Result\n\u002F\u002F an error with this tag becomes a Success, everything else passes unchanged\nconst catchTag = (tag, handler) => (result) =>\n  result._tag === 'Failure' && result.error._tag === tag ? succeed(handler(result.error)) : result\n\nconst ids = [1, 2, 3]\nids.forEach((id) => {\n  const result = catchTag('UserNotFound', () => 'guest')(findOnline(id))\n  console.log(`${id}: ${show(result)}`)\n})\n\n\u002F\u002F nobody handled UserOffline: the error stayed in the result,\n\u002F\u002F just as in Effect it would stay in the E type",{"ru":7,"en":196},"1: Success (John)\n2: Failure (UserOffline)\n3: Success (guest)",25,{"slug":199,"title":200},"neural-networks",{"ru":7,"en":201},"Neural networks and category theory",{"slug":203,"title":204},"selecting-library",{"ru":7,"en":205},"How to choose an FP library",1792684725090]