{"id":25721274,"url":"https://github.com/kenato254/ts-option","last_synced_at":"2026-04-11T05:31:36.252Z","repository":{"id":279067044,"uuid":"937530235","full_name":"Kenato254/ts-option","owner":"Kenato254","description":"The Option type is a powerful tool for handling values that may or may not be present, inspired by functional programming languages like Rust and Haskell. It provides a type-safe way to avoid common errors associated with null or undefined by explicitly representing the absence of a value.","archived":false,"fork":false,"pushed_at":"2025-02-23T15:04:45.000Z","size":58,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-23T15:32:12.468Z","etag":null,"topics":["ci","functional-programming","github-actions","javascript","nodejs","npm","safety","typescript","yarn"],"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/Kenato254.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-23T09:34:53.000Z","updated_at":"2025-02-23T15:04:47.000Z","dependencies_parsed_at":"2025-02-23T15:32:14.787Z","dependency_job_id":"fcb48e61-1041-455f-bfd9-3b4f4298370a","html_url":"https://github.com/Kenato254/ts-option","commit_stats":null,"previous_names":["kenato254/ts-option"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Kenato254/ts-option","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kenato254%2Fts-option","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kenato254%2Fts-option/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kenato254%2Fts-option/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kenato254%2Fts-option/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Kenato254","download_url":"https://codeload.github.com/Kenato254/ts-option/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kenato254%2Fts-option/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260718586,"owners_count":23051914,"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":["ci","functional-programming","github-actions","javascript","nodejs","npm","safety","typescript","yarn"],"created_at":"2025-02-25T18:35:31.215Z","updated_at":"2025-12-30T20:06:50.942Z","avatar_url":"https://github.com/Kenato254.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Option Type in TypeScript\n\n[![CI/CD](https://github.com/kenato254/ts-option/actions/workflows/ci.yml/badge.svg)](https://github.com/kenato254/ts-option/actions/workflows/ci.yml)\n[![Coverage](https://codecov.io/gh/kenato254/ts-option/branch/main/graph/badge.svg)](https://codecov.io/gh/kenato254/ts-option)\n\nThe `Option` type is a powerful tool for handling values that may or may not be present, inspired by functional programming languages like Rust and Haskell. It provides a type-safe way to avoid common errors associated with `null` or `undefined` by explicitly representing the absence of a value.\n\n## Table of Contents\n\n- [Option Type in TypeScript](#option-type-in-typescript)\n  - [Table of Contents](#table-of-contents)\n  - [Introduction](#introduction)\n    - [Why Use It?](#why-use-it)\n  - [Integration Instructions](#integration-instructions)\n    - [Example](#example)\n    - [Benefits Highlight](#benefits-highlight)\n    - [Key Points for the Team](#key-points-for-the-team)\n  - [Basic Usage](#basic-usage)\n    - [Creating Option](#creating-option)\n    - [Checking Option](#checking-option)\n    - [Transforming Option](#transforming-option)\n    - [Unwrapping Option](#unwrapping-option)\n    - [Advanced Usage](#advanced-usage)\n      - [Filtering](#filtering)\n      - [Fallbacks](#fallbacks)\n  - [Benefits](#benefits)\n  - [Naive Example](#naive-example)\n\n## Introduction\n\nThe `Option\u003cT\u003e` type represents a value that can either be `Some\u003cT\u003e` (containing a value of type `T`) or `None` (representing the absence of a value). This approach helps prevent runtime errors by forcing developers to handle both cases explicitly.\n\n### Why Use It?\n\n- **Type Safety**: Ensures that you handle both `Some` and `None` cases.\n- **Error Reduction**: Avoids common bugs related to `null` or `undefined`.\n- **Explicit Handling**: Makes the code more readable by clearly indicating where values might be absent.\n\n## Integration Instructions\n\nTo integrate the `Option` type into your existing TypeScript project:\n\n1. **Add the `Option` Module**: Copy the `Option` type and its utility functions into a shared module or utility file.\n2. **Convert Nullable Values**: Use the `fromNullable` function to convert existing values that might be `null` or `undefined` into `Option\u003cT\u003e`.\n3. **Replace Null Checks**: Replace traditional `null` or `undefined` checks with `isSome` and `isNone` functions.\n\n### Example\n\n```typescript\nimport { Option, some, none, isSome, fromNullable } from './option';\n\nfunction getSomeValue(): string | null {\n  return Math.random() \u003e 0.5 ? 'Hello' : null;\n}\n\nconst maybeValue: Option\u003cstring\u003e = fromNullable(getSomeValue());\nif (isSome(maybeValue)) {\n  console.log(maybeValue.value);  // Safely access the value\n} else {\n  console.log('No value present');\n}\n```\n\n### Benefits Highlight\n\nImproved code safety and readability, reducing the need for defensive null checks.\n\n### Key Points for the Team\n\n- Always handle both `Some` and `None` cases.\n- Use utility functions like `map`, `flatMap`, and `unwrapOr` to work with `Option` values.\n- Avoid using `unwrap` unless you are certain the value is `Some`, or handle the potential error.\n\n## Basic Usage\n\n### Creating Option\n\n- `some\u003cT\u003e(value: T)`: Creates an Option containing a value.\n- `none()`: Creates an Option representing no value.\n\n### Checking Option\n\n- `isSome\u003cT\u003e(option: Option\u003cT\u003e)`: Returns true if the option is Some.\n- `isNone\u003cT\u003e(option: Option\u003cT\u003e)`: Returns true if the option is None.\n\n### Transforming Option\n\n- `map\u003cT, U\u003e(option: Option\u003cT\u003e, fn: (value: T) =\u003e U)`: Applies a function to the value if Some, otherwise returns None.\n- `flatMap\u003cT, U\u003e(option: Option\u003cT\u003e, fn: (value: T) =\u003e Option\u003cU\u003e)`: Chains operations that return Option.\n\n### Unwrapping Option\n\n- `unwrapOr\u003cT\u003e(option: Option\u003cT\u003e, defaultValue: T)`: Returns the value if Some, otherwise returns the default.\n- `unwrap\u003cT\u003e(option: Option\u003cT\u003e, message?: string)`: Returns the value if Some, otherwise throws an OptionError.\n\n### Advanced Usage\n\n#### Filtering\n\n- `filter\u003cT\u003e(option: Option\u003cT\u003e, predicate: (value: T) =\u003e boolean)`: Returns Some if the value passes the predicate, otherwise None.\n\n#### Fallbacks\n\n- `orElse\u003cT\u003e(option: Option\u003cT\u003e, alternative: () =\u003e Option\u003cT\u003e)`: Returns the option if Some, otherwise computes and returns the alternative.\n\n## Benefits\n\n1. **Type Safety**: The TypeScript compiler ensures you handle both Some and None, preventing access to absent values.\n2. **Error Reduction**: Eliminates runtime errors caused by accessing null or undefined.\n3. **Code Clarity**: Makes the intent clear—whether a value is optional—and reduces boilerplate null checks.\n4. **Functional Programming**: Encourages functional patterns like mapping and chaining, leading to cleaner, more composable code.\n\n## Naive Example\n\n```typescript\nimport {\n  Option,\n  some,\n  none,\n  isSome,\n  isNone,\n  map,\n  flatMap,\n  filter,\n  unwrap,\n  unwrapOr,\n  fromNullable,\n  and,\n  or,\n  liftA2,\n  matchOption,\n  mapWithDefault,\n} from 'ts-option';\n\n// In-memory user database\nlet userID = 0;\nconst userDB: User[] = [];\n\ntype User = {\n  id: number;\n  name: string;\n  email: string;\n};\n\n// Create a user with validation\nfunction createUser(name: string, email: string): Option\u003cUser\u003e {\n  if (name.trim().length \u003c 3 || !email.includes('@')) {\n    return none();\n  }\n  const user = { id: ++userID, name, email };\n  userDB.push(user);\n  return some(user);\n}\n\n// Get user by email\nfunction getUserByEmail(userEmail: string): Option\u003cUser\u003e {\n  return fromNullable(userDB.find((user) =\u003e user.email === userEmail));\n}\n\n// Get user by ID\nfunction getUserById(userId: number): Option\u003cUser\u003e {\n  return fromNullable(userDB.find((user) =\u003e user.id === userId));\n}\n\n// Update user\nfunction updateUser(user: User): Option\u003cUser\u003e {\n  const index = userDB.findIndex((u) =\u003e u.id === user.id);\n  if (index === -1) {\n    return none();\n  }\n  userDB[index] = user;\n  return some(user);\n}\n\n// Delete user by ID\nfunction deleteUser(userId: number): Option\u003cUser\u003e {\n  const index = userDB.findIndex((u) =\u003e u.id === userId);\n  if (index === -1) {\n    return none();\n  }\n  const user = userDB.splice(index, 1)[0];\n  return some(user);\n}\n\n// Example usage with all Option functionalities\n(() =\u003e {\n  // Create users\n  const user1 = createUser('Alice', 'alice@example.com');\n  const user2 = createUser('Bob', 'bob@example.com');\n  \n  const invalidUser = createUser('C', 'charlie');\n\n  // Check if users exist\n  console.log('User1 exists:', isSome(user1)); // true\n  console.log('Invalid user exists:', isNone(invalidUser)); // true\n\n  // Transform user data with map\n  const userName = map(user1, (u) =\u003e u.name);\n  console.log('User1 name:', unwrapOr(userName, 'Unknown')); // 'Alice'\n\n  // Chain operations with flatMap\n  const updatedUser = flatMap(user1, (u) =\u003e\n    updateUser({ ...u, name: 'Alicia' })\n  );\n  console.log('Updated user:', unwrapOr(updatedUser, null)); // { id: 1, name: 'Alicia', email: 'alice@example.com' }\n\n  // Filter users\n  const longNameUser = filter(user2, (u) =\u003e u.name.length \u003e 3);\n  console.log('Long name user:', unwrapOr(longNameUser, null)); // { id: 2, name: 'Bob', email: 'bob@example.com' }\n\n  // Handle non-existent user with unwrap and error\n  const nonExistentUser = getUserByEmail('nonexistent@mail.com');\n  try {\n    unwrap(nonExistentUser);\n  } catch (e) {\n    console.log('Error:', (e as Error).message); // 'Attempted to unwrap a None value'\n  }\n\n  // Provide default with unwrapOr\n  const defaultUser = unwrapOr(nonExistentUser, {\n    id: ++userID,\n    name: 'Guest',\n    email: 'guest@example.com',\n  });\n  console.log('Default user:', defaultUser); // { id: 3, name: 'Guest', email: 'guest@example.com' }\n\n  // Combine two options with and\n  const userPair = and(user1, user2);\n  console.log('User pair:', unwrapOr(userPair, null)); // [{ id: 1, ... }, { id: 2, ... }]\n\n  // Fallback with or\n  const fallbackUser = or(nonExistentUser, some(defaultUser));\n  console.log('Fallback user:', unwrapOr(fallbackUser, null)); // { id: 3, name: 'Guest', ... }\n\n  // Combine values with liftA2\n  const combinedNames = liftA2(\n    (u1: User, u2: User) =\u003e `${u1.name} \u0026 ${u2.name}`,\n    user1,\n    user2\n  );\n  console.log('Combined names:', unwrapOr(combinedNames, 'No pair')); // 'Alicia \u0026 Bob'\n\n  // Match cases with matchOption\n  const matched = matchOption(\n    nonExistentUser,\n    (u) =\u003e some(`Found: ${u.name}`),\n    () =\u003e some('No user found')\n  );\n  console.log('Matched result:', unwrap(matched)); // 'No user found'\n\n  // Map with default value\n  const nameWithDefault = mapWithDefault(user1, (u) =\u003e u.name.toUpperCase(), 'N/A');\n  console.log('Name with default:', unwrap(nameWithDefault)); // 'ALICIA'\n\n  // Delete a user\n  const deletedUser = deleteUser(1);\n  console.log('Deleted user:', unwrapOr(deletedUser, null)); // { id: 1, name: 'Alicia', ... }\n\n  // Display current database\n  console.log('Current DB:', userDB); // [{ id: 2, name: 'Bob', ... }]\n})();\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkenato254%2Fts-option","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkenato254%2Fts-option","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkenato254%2Fts-option/lists"}