{"id":13452527,"url":"https://github.com/gcanti/monocle-ts","last_synced_at":"2025-05-14T13:05:52.601Z","repository":{"id":40680401,"uuid":"81648352","full_name":"gcanti/monocle-ts","owner":"gcanti","description":"Functional optics: a (partial) porting of Scala monocle","archived":false,"fork":false,"pushed_at":"2022-12-09T10:12:08.000Z","size":1462,"stargazers_count":1064,"open_issues_count":43,"forks_count":54,"subscribers_count":22,"default_branch":"master","last_synced_at":"2025-05-01T16:01:38.394Z","etag":null,"topics":["functional-programming","lenses","optics","typescript"],"latest_commit_sha":null,"homepage":"https://gcanti.github.io/monocle-ts/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gcanti.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-02-11T11:21:38.000Z","updated_at":"2025-04-18T05:42:49.000Z","dependencies_parsed_at":"2023-01-25T21:01:14.375Z","dependency_job_id":null,"html_url":"https://github.com/gcanti/monocle-ts","commit_stats":null,"previous_names":[],"tags_count":53,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gcanti%2Fmonocle-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gcanti%2Fmonocle-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gcanti%2Fmonocle-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gcanti%2Fmonocle-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gcanti","download_url":"https://codeload.github.com/gcanti/monocle-ts/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253749430,"owners_count":21958120,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["functional-programming","lenses","optics","typescript"],"created_at":"2024-07-31T07:01:26.618Z","updated_at":"2025-05-14T13:05:52.569Z","avatar_url":"https://github.com/gcanti.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","FpTs","Domain modeling in TypeScript by Benoit Ruiz"],"sub_categories":["gcanti/monocle-ts"],"readme":"[![build status](https://img.shields.io/travis/gcanti/monocle-ts/master.svg?style=flat-square)](https://travis-ci.org/gcanti/monocle-ts)\n[![dependency status](https://img.shields.io/david/gcanti/monocle-ts.svg?style=flat-square)](https://david-dm.org/gcanti/monocle-ts)\n![npm downloads](https://img.shields.io/npm/dm/monocle-ts.svg)\n\n# Motivation\n\n(Adapted from [monocle site](https://www.optics.dev/Monocle/))\n\nModifying immutable nested object in JavaScript is verbose which makes code difficult to understand and reason about.\n\nLet's have a look at some examples:\n\n```ts\ninterface Street {\n  num: number\n  name: string\n}\ninterface Address {\n  city: string\n  street: Street\n}\ninterface Company {\n  name: string\n  address: Address\n}\ninterface Employee {\n  name: string\n  company: Company\n}\n```\n\nLet’s say we have an employee and we need to upper case the first character of his company street name. Here is how we\ncould write it in vanilla JavaScript\n\n```ts\nconst employee: Employee = {\n  name: 'john',\n  company: {\n    name: 'awesome inc',\n    address: {\n      city: 'london',\n      street: {\n        num: 23,\n        name: 'high street'\n      }\n    }\n  }\n}\n\nconst capitalize = (s: string): string =\u003e s.substring(0, 1).toUpperCase() + s.substring(1)\n\nconst employeeCapitalized = {\n  ...employee,\n  company: {\n    ...employee.company,\n    address: {\n      ...employee.company.address,\n      street: {\n        ...employee.company.address.street,\n        name: capitalize(employee.company.address.street.name)\n      }\n    }\n  }\n}\n```\n\nAs we can see copy is not convenient to update nested objects because we need to repeat ourselves. Let's see what could\nwe do with `monocle-ts`\n\n```ts\nimport { Lens } from 'monocle-ts'\n\nconst company = Lens.fromProp\u003cEmployee\u003e()('company')\nconst address = Lens.fromProp\u003cCompany\u003e()('address')\nconst street = Lens.fromProp\u003cAddress\u003e()('street')\nconst name = Lens.fromProp\u003cStreet\u003e()('name')\n```\n\n`compose` takes two `Lenses`, one from `A` to `B` and another one from `B` to `C` and creates a third `Lens` from `A` to\n`C`. Therefore, after composing `company`, `address`, `street` and `name`, we obtain a `Lens` from `Employee` to\n`string` (the street name). Now we can use this `Lens` issued from the composition to modify the street name using the\nfunction `capitalize`\n\n```ts\nconst capitalizeName = company.compose(address).compose(street).compose(name).modify(capitalize)\n\nassert.deepStrictEqual(capitalizeName(employee), employeeCapitalized)\n```\n\nYou can use the `fromPath` API to avoid some boilerplate\n\n```ts\nimport { Lens } from 'monocle-ts'\n\nconst name = Lens.fromPath\u003cEmployee\u003e()(['company', 'address', 'street', 'name'])\n\nconst capitalizeName = name.modify(capitalize)\n\nassert.deepStrictEqual(capitalizeName(employee), employeeCapitalized) // true\n```\n\nHere `modify` lift a function `string =\u003e string` to a function `Employee =\u003e Employee`. It works but it would be clearer\nif we could zoom into the first character of a `string` with a `Lens`. However, we cannot write such a `Lens` because\n`Lenses` require the field they are directed at to be _mandatory_. In our case the first character of a `string` is\noptional as a `string` can be empty. So we need another abstraction that would be a sort of partial Lens, in\n`monocle-ts` it is called an `Optional`.\n\n```ts\nimport { Optional } from 'monocle-ts'\nimport { some, none } from 'fp-ts/Option'\n\nconst firstLetterOptional = new Optional\u003cstring, string\u003e(\n  (s) =\u003e (s.length \u003e 0 ? some(s[0]) : none),\n  (a) =\u003e (s) =\u003e (s.length \u003e 0 ? a + s.substring(1) : s)\n)\n\nconst firstLetter = company.compose(address).compose(street).compose(name).asOptional().compose(firstLetterOptional)\n\nassert.deepStrictEqual(firstLetter.modify((s) =\u003e s.toUpperCase())(employee), employeeCapitalized)\n```\n\nSimilarly to `compose` for lenses, `compose` for optionals takes two `Optionals`, one from `A` to `B` and another from\n`B` to `C` and creates a third `Optional` from `A` to `C`. All `Lenses` can be seen as `Optionals` where the optional\nelement to zoom into is always present, hence composing an `Optional` and a `Lens` always produces an `Optional`.\n\n# TypeScript compatibility\n\nThe stable version is tested against TypeScript 3.5.2, but should run with TypeScript 2.8.0+ too\n\n| `monocle-ts` version | required `typescript` version |\n| -------------------- | ----------------------------- |\n| 2.0.x+               | 3.5+                          |\n| 1.x+                 | 2.8.0+                        |\n\n**Note**. If you are running `\u003c typescript@3.0.1` you have to polyfill `unknown`.\n\nYou can use [unknown-ts](https://github.com/gcanti/unknown-ts) as a polyfill.\n\n# Documentation\n\n- [API Reference](https://gcanti.github.io/monocle-ts/)\n\n## Experimental modules (version `2.3+`)\n\nExperimental modules (\\*) are published in order to get early feedback from the community.\n\nThe experimental modules are **independent and backward-incompatible** with stable ones.\n\n(\\*) A feature tagged as _Experimental_ is in a high state of flux, you're at risk of it changing without notice.\n\nFrom `monocle@2.3+` you can use the following experimental modules:\n\n- `Iso`\n- `Lens`\n- `Prism`\n- `Optional`\n- `Traversal`\n- `At`\n- `Ix`\n\nwhich implement the same features contained in `index.ts` but are `pipe`-based instead of `class`-based.\n\nHere's the same examples with the new API\n\n```ts\ninterface Street {\n  num: number\n  name: string\n}\ninterface Address {\n  city: string\n  street: Street\n}\ninterface Company {\n  name: string\n  address: Address\n}\ninterface Employee {\n  name: string\n  company: Company\n}\n\nconst employee: Employee = {\n  name: 'john',\n  company: {\n    name: 'awesome inc',\n    address: {\n      city: 'london',\n      street: {\n        num: 23,\n        name: 'high street'\n      }\n    }\n  }\n}\n\nconst capitalize = (s: string): string =\u003e s.substring(0, 1).toUpperCase() + s.substring(1)\n\nconst employeeCapitalized = {\n  ...employee,\n  company: {\n    ...employee.company,\n    address: {\n      ...employee.company.address,\n      street: {\n        ...employee.company.address.street,\n        name: capitalize(employee.company.address.street.name)\n      }\n    }\n  }\n}\n\nimport * as assert from 'assert'\nimport * as L from 'monocle-ts/Lens'\nimport { pipe } from 'fp-ts/function'\n\nconst capitalizeName = pipe(\n  L.id\u003cEmployee\u003e(),\n  L.prop('company'),\n  L.prop('address'),\n  L.prop('street'),\n  L.prop('name'),\n  L.modify(capitalize)\n)\n\nassert.deepStrictEqual(capitalizeName(employee), employeeCapitalized)\n\nimport * as O from 'monocle-ts/Optional'\nimport { some, none } from 'fp-ts/Option'\n\nconst firstLetterOptional: O.Optional\u003cstring, string\u003e = {\n  getOption: (s) =\u003e (s.length \u003e 0 ? some(s[0]) : none),\n  set: (a) =\u003e (s) =\u003e (s.length \u003e 0 ? a + s.substring(1) : s)\n}\n\nconst firstLetter = pipe(\n  L.id\u003cEmployee\u003e(),\n  L.prop('company'),\n  L.prop('address'),\n  L.prop('street'),\n  L.prop('name'),\n  L.composeOptional(firstLetterOptional)\n)\n\nassert.deepStrictEqual(\n  pipe(\n    firstLetter,\n    O.modify((s) =\u003e s.toUpperCase())\n  )(employee),\n  employeeCapitalized\n)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgcanti%2Fmonocle-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgcanti%2Fmonocle-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgcanti%2Fmonocle-ts/lists"}