{"id":20022299,"url":"https://github.com/lucifier129/coproduct","last_synced_at":"2025-05-05T01:31:27.660Z","repository":{"id":44823220,"uuid":"449628971","full_name":"Lucifier129/coproduct","owner":"Lucifier129","description":"A small library aims to improve better tagged-unions/discriminated-unions supporting for TypeScript","archived":false,"fork":false,"pushed_at":"2022-02-16T09:40:26.000Z","size":483,"stargazers_count":29,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-08T14:52:30.870Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/Lucifier129.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2022-01-19T09:35:19.000Z","updated_at":"2023-08-05T21:50:38.000Z","dependencies_parsed_at":"2022-09-03T04:12:00.307Z","dependency_job_id":null,"html_url":"https://github.com/Lucifier129/coproduct","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Lucifier129%2Fcoproduct","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Lucifier129%2Fcoproduct/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Lucifier129%2Fcoproduct/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Lucifier129%2Fcoproduct/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Lucifier129","download_url":"https://codeload.github.com/Lucifier129/coproduct/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252423174,"owners_count":21745553,"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":[],"created_at":"2024-11-13T08:39:51.645Z","updated_at":"2025-05-05T01:31:26.510Z","avatar_url":"https://github.com/Lucifier129.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# coproduct\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"400\" src=\"./resource/coproduct-logos/coproduct-logos.jpeg\"\u003e\n\u003c/p\u003e\n\n[![npm version](https://img.shields.io/npm/v/coproduct.svg?style=flat)](https://www.npmjs.com/package/coproduct)\n![coproduct workflow](https://github.com/Lucifier129/coproduct/actions/workflows/main.yml/badge.svg)\n[![Documentation](https://img.shields.io/badge/documentation-yes-brightgreen.svg)](https://github.com/Lucifier129/coproduct#readme)\n[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/Lucifier129/coproduct/graphs/commit-activity)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/Lucifier129/coproduct/blob/master/LICENSE)\n[![Twitter: guyingjie129](https://img.shields.io/twitter/follow/guyingjie129.svg?style=social)](https://twitter.com/guyingjie129)\n\n\u003e A small library aims to improve better tagged-unions/discriminated-unions supporting for TypeScript\n\n## Benefits\n\n- Small bundled size(just 1kb)\n- Easy to use with just a few apis to learn\n- Improving **Type-Safety** for your TypeScript project via exhaustive pattern-matching\n\n## Installation\n\n```shell\nyarn add coproduct\nnpm install --save coproduct\n```\n\n## Usage\n\nFor redux app\n\n```typescript\n// state type\ntype CounterState = {\n  count: number;\n};\n\n// action type\ntype CounterAction =\n  | {\n      type: 'incre';\n    }\n  | {\n      type: 'decre';\n    }\n  | {\n      type: 'increBy';\n      step: number;\n    }\n  | {\n      type: 'decreBy';\n      step: number;\n    };\n\n// reducer with match\nconst counterReducer = (\n  state: CounterState,\n  action: CounterAction\n): CounterState =\u003e {\n  return match(action).case({\n    incre: () =\u003e ({\n      ...state,\n      count: state.count + 1,\n    }),\n    decre: () =\u003e ({\n      ...state,\n      count: state.count - 1,\n    }),\n    increBy: ({ step }) =\u003e ({\n      ...state,\n      count: state.count + step,\n    }),\n    decreBy: ({ step }) =\u003e ({\n      ...state,\n      count: state.count - step,\n    }),\n  });\n};\n\n// reducer without match\nconst counterReducer = (\n  state: CounterState,\n  action: CounterAction\n): CounterState =\u003e {\n  if (action.type === 'incre') {\n    return {\n      ...state,\n      count: state.count + 1,\n    };\n  } else if (action.type === 'decre') {\n    return {\n      ...state,\n      count: state.count - 1,\n    };\n  } else if (action.type === 'increBy') {\n    return {\n      ...state,\n      count: state.count + action.step,\n    };\n  } else if (action.type === 'decreBy') {\n    return {\n      ...state,\n      count: state.count - action.step,\n    };\n  }\n\n  throw new Error(`Unexpected action: ${action}`);\n};\n```\n\nBasic usage\n\n```typescript\nimport { match } from 'coproduct';\n\nexport type Option\u003cT\u003e = {\n  type: 'Some',\n  value: T\n} | {\n  type: 'None'\n}\n\nexport const None = {\n  type: 'None' as const;\n}\nexport const Some = \u003cT\u003e(value: T) =\u003e ({\n  type: 'Some' as const,\n  value,\n});\n\nconst show = \u003cT\u003e(data: Option\u003cT\u003e) =\u003e {\n  return match(data).case({\n    Some: data =\u003e `some: ${data.value}`,\n    None: () =\u003e 'none',\n  });\n};\n\nconst value0 = Some(1);\nconst value1 = None;\n\nexpect(show(value0)).toBe('some: 1');\nexpect(show(value1)).toBe('none');\n\n// you can use if/else to match manually if you want\nconst show = \u003cT\u003e(data: Option\u003cT\u003e) =\u003e {\n  if (data.type === 'Some') {\n    return `some: ${data.some}`;\n  } else if (data.type === 'None') {\n    return 'none';\n  }\n  throw new Error(`Unexpected data: ${data}`);\n};\n```\n\nYou don't need to define your own `option type`, coproduct has built-in `Option` and `Result`.\n\n```typescript\nimport { match, Option, Some, None, Result, Ok, Err } from 'coproduct';\n\nconst show = \u003cT\u003e(data: Option\u003cT\u003e) =\u003e {\n  return match(data).case({\n    Some: data =\u003e `some: ${data.value}`,\n    None: () =\u003e 'none',\n  });\n};\n\nexpect(show(Some(1))).toBe('some: 1');\nexpect(show(None)).toBe('none');\n\nconst showResult = \u003cT\u003e(result: Result\u003cT\u003e) =\u003e {\n  return match(result).case({\n    Ok: data =\u003e `ok: ${data.value}`,\n    Err: error =\u003e `err: ${error.info}`,\n  });\n};\n\nexpect(showResult(Ok(1))).toBe('ok: 1');\nexpect(showResult(Err('error'))).toBe('err: error');\n```\n\n## Api\n\n### match(data).case(patterns)\n\n`match(data).case(patterns)` perform `exhaustive pattern-matching` for data, every case in `data` should has its own visitor function.\n\n**Note**: you can use `_: () =\u003e R` as default handler for unmatched case.\n\n### createMatch(tagField) =\u003e match\n\nYou can create your own `match` function with `tagField` to match your data.\n\nThe default `match` of `coproduct` was created via `createMatch('type')`\n\n```ts\nconst match = createMatch('tag');\n\ntype Data =\n  | {\n      tag: 'a';\n      value: string;\n    }\n  | {\n      tag: 'b';\n      value: number;\n    };\n\nconst handleData = (data: Data) =\u003e {\n  return match(data).case({\n    a: data =\u003e `a: ${data.value}`,\n    b: data =\u003e `b: ${data.value}`,\n  });\n};\n\nhandleData({ tag: 'a', value: 'hello' }); // 'a: hello'\nhandleData({ tag: 'b', value: 1 }); // 'b: 1'\n```\n\n### Some(value)\n\n`Some(value)` return the value with the `Some\u003cT\u003e` case of `Option Type`.\n\n### None\n\n`None` is the value with the `None` case of `Option Type`\n\n### Ok(value)\n\n`Ok(value)` return the value with the `Ok\u003cT\u003e` case of `Result Type`.\n\n### Err(message)\n\n`Err(message)` return the value with the `Err\u003cE\u003e` case of `Result Type`.\n\n## Caveats\n\n- The name `$tag` is reserved for `$tag` property of tagged object, it can't be used as a tag name.\n- The symbol `_` can't be used as a tag name since it's a reserved filed in `coproduct` as placeholder for `default` case.\n\n## Contribution Guide\n\n```shell\n# test\nnpm run test\n\n# build\nnpm run build\n```\n\n## Author\n\n👤 **Jade Gu**\n\n- Twitter: [@guyingjie129](https://twitter.com/guyingjie129)\n- Github: [@Lucifier129](https://github.com/Lucifier129)\n\n## 🤝 Contributing\n\nContributions, issues and feature requests are welcome!\n\nFeel free to check [issues page](https://github.com/Lucifier129/coproduct/issues).\n\n## Show your support\n\nGive a ⭐️ if this project helped you!\n\n## 📝 License\n\nCopyright © 2022 [Jade Gu](https://github.com/Lucifier129).\n\nThis project is [MIT](https://github.com/Lucifier129/coproduct/blob/master/LICENSE) licensed.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucifier129%2Fcoproduct","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flucifier129%2Fcoproduct","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucifier129%2Fcoproduct/lists"}