{"name":"ts-algebra","version":"1.1.0-beta.0","description":"Types on steroids 💊","main":"lib/index.d.ts","scripts":{"release":"bash scripts/release.bash","test":"tsc --noEmit"},"dependencies":{"ts-toolbelt":"^9.6.0"},"devDependencies":{"rollup":"^2.67.3","rollup-plugin-dts":"4.1.0","rollup-plugin-import-map":"^2.2.2","typescript":"^4.5.5"},"author":{"name":"Thomas Aribart"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/ThomasAribart/ts-algebra.git"},"keywords":["typescript","type","ts"],"bugs":{"url":"https://github.com/ThomasAribart/ts-algebra/issues"},"homepage":"https://github.com/ThomasAribart/ts-algebra#readme","readme":"<img src=\"assets/header-round-medium.png\" width=\"100%\" align=\"center\" />\n\n<p align=\"right\">\n  <i>If you use this repo, star it ✨</i>\n</p>\n\n# Types on steroids 💊\n\n`ts-algebra` exposes a subset of TS types called **Meta-types**: Meta-types are types that encapsulate other types.\n\n```typescript\nimport { Meta } from \"ts-algebra\";\n\ntype MetaString = Meta.Primitive<string>;\n```\n\nThe encapsulated type can be retrieved using the `Resolve` operation.\n\n```typescript\ntype Resolved = Meta.Resolve<MetaString>;\n// => string 🙌\n```\n\nYou can also use the more compact `M` notation:\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Primitive<string>\n>;\n```\n\n## Okay, but... why ? 🤔\n\nMeta-types allow operations that **are not possible with conventional types**.\n\nFor instance, they allow new [\"intersect\"](#intersect) and [\"exclude\"](#exclude) operations, and handling objects additional properties:\n\n```typescript\ntype MyObject = {\n  str: string; // <= ❌ \"str\" is assignable to string\n  [key: string]: number;\n};\n\ntype MyObjectKeys = keyof MyObject;\n// => string <= ❌ Unable to isolate \"str\"\n```\n\nThink of meta-types as a parallel universe where all kinds of magic can happen 🌈 Once your computations are over, you can retrieve the results by resolving them.\n\n<img src=\"assets/schema.png\" width=\"100%\" align=\"center\" />\n\n> Meta-types were originally part of [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts). Check it to see a real-life usage.\n\n## Table of content\n\n- [Installation](#%EF%B8%8F-installation)\n- [Cardinality](#-cardinality)\n- [Meta-types](#-meta-types)\n  - [Any](#any)\n  - [Never](#never)\n  - [Const](#const)\n  - [Enum](#enum)\n  - [Primitive](#primitive)\n  - [Array](#array)\n  - [Tuple](#tuple)\n  - [Object](#object)\n  - [Union](#union)\n- [Methods](#-methods)\n  - [Resolve](#resolve)\n  - [Intersect](#intersect)\n  - [Exclude](#exclude)\n- [Type constraints](#-type-constraints)\n- [Unsafe types](#%EF%B8%8F-unsafe-types-and-methods)\n\n## ☁️ Installation\n\n```bash\n# npm\nnpm install --save-dev ts-algebra\n\n# yarn\nyarn add --dev ts-algebra\n```\n\n## 🧮 Cardinality\n\nA bit of theory first:\n\n- The [**cardinality**](https://en.wikipedia.org/wiki/Cardinality) of a type is the number of distinct values (potentially infinite) that can be assigned to it\n- A meta-type is said **representable** if at least one value can be assigned to its resolved type (cardinality ≥ 1)\n\nAn important notion to keep in mind using `ts-algebra`:\n\n---\n\n<p align=\"center\">\n  <a href=\"#never\"><code>M.Never</code></a> is the only Meta-Type that is non-representable\n  <br>\n  <i>(i.e. that resolves to <code>never</code>)</i>\n</p>\n\n---\n\nAny other non-representable meta-type (e.g. an object with a non-representable but required property) will be instanciated as `M.Never`.\n\nThere are drawbacks to this choice (the said property is hard to find and debug) but stronger benefits: This drastically reduces type computations, in particular in [intersections](#intersect) and [exclusions](#exclude). This is crucial for performances and stability.\n\n## ✨ Meta-types\n\n### Any\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Any\n>;\n// => unknown\n```\n\n### Never\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Never\n>;\n// => never\n```\n\n### Const\n\nUsed for types with [cardinalities](#meta-types) of 1.\n\n**Arguments:**\n\n- <code>Value <i>(type)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Const<\"I love pizza\">\n>;\n// => \"I love pizza\"\n```\n\n### Enum\n\nUsed for types with finite [cardinalities](#meta-types).\n\n**Arguments:**\n\n- <code>Values <i>(type union)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Food = M.Resolve<\n  M.Enum<\"pizza\" | \"tacos\" | \"fries\">\n>;\n// => \"pizza\" | \"tacos\" | \"fries\"\n```\n\n> ☝️ `M.Enum<never>` is [non-representable](#✨-meta-types)\n\n### Primitive\n\nUsed for either `string`, `number`, `boolean` or `null`.\n\n**Arguments:**\n\n- <code>Value <i>(string | number | boolean | null)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Primitive<string>\n>;\n// => string\n```\n\n### Array\n\nUsed for lists of items of the same type.\n\n**Arguments:**\n\n- <code>Items <i>(?meta-type = M.Any)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Array\n>;\n// => unknown[]\n\ntype Resolved = M.Resolve<\n  M.Array<M.Primitive<string>>\n>;\n// => string[]\n```\n\n> ☝️ Any meta-array is representable by `[]`\n\n### Tuple\n\nUsed for finite, ordered lists of items of different types.\n\nMeta-tuples can have **additional items**, typed as [`M.Never`](#never) by default. Thus, any meta-tuple is considered **closed** (additional items not allowed), unless a representable additional items meta-type is specified, in which case it becomes **open**.\n\n**Arguments:**\n\n- <code>RequiredItems <i>(meta-type[])</i>:</code>\n- <code>AdditionalItems <i>(?meta-type = M.Never)</i>:</code> Type of additional items\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Tuple<[M.Primitive<string>]>\n>;\n// => [string]\n\ntype Resolved = M.Resolve<\n  M.Tuple<\n    [M.Primitive<string>],\n    M.Primitive<string>\n  >\n>;\n// => [string, ...string[]]\n```\n\n> ☝️ A meta-tuple is [non-representable](#✨-meta-types) if one of its required items is non-representable\n\n### Object\n\nUsed for sets of key-value pairs (properties) which can be required or not.\n\nMeta-objects can have **additional properties**, typed as [`M.Never`](#never) by default. Thus, any meta-object is considered **closed** (additional properties not allowed), unless a representable additional properties meta-type is specified, in which case it becomes **open**.\n\nIn presence of named properties, open meta-objects additional properties are resolved as `unknown` to avoid conflicts. However, they are used as long as the meta-type is not resolved (especially in [intersections](#intersect) and [exclusions](#exclude)).\n\n**Arguments:**\n\n- <code>NamedProperties <i>(?{ [key:string]: meta-type } = {})</i></code>\n- <code>RequiredPropertiesKeys <i>(?string union = never)</i></code>\n- <code>AdditionalProperties <i>(?meta-type = M.Never)</i>:</code> The type of additional properties\n\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Object<\n    {\n      required: M.Primitive<string>;\n      notRequired: M.Primitive<null>;\n    },\n    \"required\",\n    M.Primitive<number>\n  >\n>;\n// => {\n//  req: string,\n//  notRequired?: null,\n//  [key: string]: unknown\n// }\n```\n\n> ☝️ A meta-object is [non-representable](#✨-meta-types) if one of its required properties value is non-representable:\n>\n> - If it is a non-representable named property\n> - If it is an additional property, and the object is closed\n\n### Union\n\nUsed to combine meta-types in a union of meta-types.\n\n**Arguments:**\n\n- <code>Values <i>(meta-type union)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Food = M.Resolve<\n  M.Union<\n    | M.Primitive<number>\n    | M.Enum<\"pizza\" | \"tacos\" | \"fries\">\n    | M.Const<true>\n  >\n>;\n// => number\n// | \"pizza\" | \"tacos\" | \"fries\"\n// | true\n```\n\n> ☝️ A meta-union is [non-representable](#✨-meta-types) if it is empty, or if none of its elements is representable\n\n## 🔧 Methods\n\n### Resolve\n\nResolves the meta-type to its encapsulated type.\n\n**Arguments:**\n\n- <code>MetaType <i>(meta-type)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Resolved = M.Resolve<\n  M.Primitive<string>\n>;\n// => string\n```\n\n### Intersect\n\nTakes two meta-types as arguments, and returns their intersection as a meta-type.\n\n**Arguments:**\n\n- <code>LeftMetaType <i>(meta-type)</i></code>\n- <code>RightMetaType <i>(meta-type)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Intersected = M.Intersect<\n  M.Primitive<string>,\n  M.Enum<\"I love pizza\"\n    | [\"tacos\"]\n    | { and: \"fries\" }\n  >\n>\n// => M.Enum<\"I love pizza\">\n```\n\nMeta-type intersections differ from conventional intersections:\n\n<!-- prettier-ignore -->\n```typescript\ntype ConventionalIntersection =\n  { str: string } & { num: number };\n// => { str: string, num: number }\n\ntype MetaIntersection = M.Intersect<\n  M.Object<\n    { str: M.Primitive<string> },\n    \"str\"\n  >,\n  M.Object<\n    { num: M.Primitive<number> },\n    \"num\"\n  >\n>;\n// => M.Never: \"num\" is required in B\n// ...but denied in A\n```\n\nIntersections are recursively propagated among tuple items and object properties, and take into account additional items and properties:\n\n<!-- prettier-ignore -->\n```typescript\ntype Intersected = M.Intersect<\n  M.Tuple<\n    [M.Primitive<number>],\n    M.Primitive<string>\n  >,\n  M.Tuple<\n    [M.Enum<\"pizza\" | 42>],\n    M.Enum<\"fries\" | true>\n  >\n>;\n// => M.Tuple<\n//  [M.Enum<42>],\n//  M.Enum<\"fries\">\n// >\n\ntype Intersected = M.Intersect<\n  M.Object<\n    { food: M.Primitive<string> },\n    \"food\",\n    M.Any\n  >,\n  M.Object<\n    { age: M.Primitive<number> },\n    \"age\",\n    M.Enum<\"pizza\" | \"fries\" | 42>\n  >\n>;\n// => M.Object<\n//  {\n//    food: M.Enum<\"pizza\" | \"fries\">,\n//    age: M.Primitive<number>\n//  },\n//  \"food\" | \"age\",\n//  M.Enum<\"pizza\" | \"fries\" | 42>\n// >\n```\n\nIntersections are distributed among unions:\n\n<!-- prettier-ignore -->\n```typescript\ntype Intersected = M.Intersect<\n  M.Primitive<string>,\n  M.Union<\n    | M.Const<\"pizza\">\n    | M.Const<42>\n  >\n>;\n// => M.Union<\n//  | M.Const<\"pizza\">\n//  | M.Never\n// >\n```\n\n### Exclude\n\nTakes two meta-types as arguments, and returns their exclusion as a meta-type.\n\n**Arguments:**\n\n- <code>SourceMetaType <i>(meta-type)</i></code>\n- <code>ExcludedMetaType <i>(meta-type)</i></code>\n\n<!-- prettier-ignore -->\n```typescript\nimport { M } from \"ts-algebra\";\n\ntype Excluded = M.Exclude<\n  M.Enum<\"I love pizza\"\n    | [\"tacos\"]\n    | { and: \"fries\" }\n  >,\n  M.Primitive<string>,\n>\n// => M.Enum<\n//  | [\"tacos\"]\n//  | { and: \"fries\" }\n// >\n```\n\nMeta-type exclusions differ from conventional exclusions:\n\n<!-- prettier-ignore -->\n```typescript\ntype ConventionalExclusion = Exclude<\n  { req: string; notReq?: string },\n  { req: string }\n>;\n// => never\n// ObjectA is assignable to ObjectB\n\ntype MetaExclusion = M.Exclude<\n  M.Object<\n    {\n      req: M.Primitive<string>;\n      notReq: M.Primitive<string>;\n    },\n    \"req\"\n  >,\n  M.Object<\n    { req: M.Primitive<string> },\n    \"req\"\n  >\n>;\n// => ObjectA\n// Exclusion is still representable\n```\n\n<!-- prettier-ignore -->\n```typescript\ntype ConventionalExclusion = Exclude<\n  { food: \"pizza\" | 42 },\n  { [k: string]: number }\n>;\n// => { food: \"pizza\" | 42 }\n\ntype MetaExclusion = M.Exclude<\n  M.Object<\n    { food: M.Enum<\"pizza\" | 42> },\n    \"food\"\n  >,\n  M.Object<\n    {},\n    never,\n    M.Primitive<number>\n  >\n>;\n// => M.Object<\n//  { food: M.Enum<\"pizza\"> },\n//  \"food\"\n// >\n```\n\nWhen exclusions can be collapsed on a single item or property, they are recursively propagated among tuple items and object properties, taking into account additional items and properties:\n\n<!-- prettier-ignore -->\n```typescript\ntype Excluded = M.Exclude<\n  M.Tuple<[M.Enum<\"pizza\" | 42>]>,\n  M.Tuple<[M.Primitive<number>]>\n>;\n// => M.Tuple<[M.Enum<\"pizza\">]>\n\ntype Excluded = M.Exclude<\n  M.Tuple<\n    [M.Enum<\"pizza\" | 42>],\n    M.Enum<\"fries\" | true>\n  >,\n  M.Tuple<\n    [M.Primitive<number>],\n    M.Primitive<string>\n  >\n>;\n// => TupleA\n// Exclusion is not collapsable on a single item\n\ntype Excluded = M.Exclude<\n  M.Object<\n    {\n      reqA: M.Enum<\"pizza\" | 42>;\n      reqB: M.Enum<\"pizza\" | 42>;\n    },\n    \"reqA\" | \"reqB\"\n  >,\n  M.Object<\n    {},\n    never,\n    M.Primitive<number>\n  >\n>;\n// => ObjectA\n// Exclusion is not collapsable on a single property\n```\n\nExclusions are distributed among unions:\n\n<!-- prettier-ignore -->\n```typescript\ntype Excluded = M.Exclude<\n  M.Union<\n    | M.Const<\"pizza\">\n    | M.Const<42>\n  >,\n  M.Primitive<number>\n>;\n// => M.Union<\n//  | M.Const<\"pizza\">\n//  | M.Never\n// >\n```\n\nExluding a union returns the intersection of the exclusions of all elements, applied separately:\n\n<!-- prettier-ignore -->\n```typescript\ntype Excluded = M.Exclude<\n  M.Enum<42 | \"pizza\" | true>,\n  M.Union<\n    | M.Primitive<number>\n    | M.Primitive<boolean>\n  >\n>;\n// => M.Enum<\"pizza\">\n```\n\n## 🚧 Type constraints\n\nTo prevent errors, meta-types inputs are validated against type constraints:\n\n<!-- prettier-ignore -->\n```typescript\ntype Invalid = M.Array<\n  string // <= ❌ Meta-type expected\n>;\n```\n\nIf you need to use them, all type constraints are also exported:\n\n| Meta-type     | Type constraint                                                        |\n| ------------- | :--------------------------------------------------------------------- |\n| `M.Any`       | `M.AnyType` = `M.Any`                                                  |\n| `M.Never`     | `M.NeverType` = `M.Never`                                              |\n| `M.Const`     | `M.ConstType` = `M.Const<any>`                                         |\n| `M.Enum`      | `M.EnumType` = `M.Enum<any>`                                           |\n| `M.Primitive` | `M.PrimitiveType` = `M.Primitive<null \\| boolean \\| number \\| string>` |\n| `M.Array`     | `M.ArrayType` = `M.Array<M.Type>`                                      |\n| `M.Tuple`     | `M.TupleType` = `M.Tuple<M.Type[], M.Type>`                            |\n| `M.Object`    | `M.ObjectType` = `M.Object<Record<string, M.Type>, string, M.Type>`    |\n| `M.Union`     | `M.UnionType` = `M.Union<M.Type>`                                      |\n| -             | `M.Type` = Union of the above                                          |\n\n## ✂️ Unsafe types and methods\n\nIn deep and self-referencing computations like in [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts), type constraints can become an issue, as the compiler may not be able to confirm the input type validity ahead of usage.\n\n<!-- prettier-ignore -->\n```typescript\ntype MyArray = M.Array<\n  VeryDeepTypeComputation<\n    ...\n  > // <= 💥 Type constraint can break\n>\n```\n\nFor such cases, `ts-algebra` exposes **\"unsafe\"** types and methods, that behave the same as \"safe\" ones but removing any type constraints. If you use them, beware: The integrity of the compiling is up to you 😉\n\n| Safe          | Unsafe         |\n| ------------- | -------------- |\n| `M.Any`       | -              |\n| `M.Never`     | -              |\n| `M.Const`     | -              |\n| `M.Enum`      | -              |\n| `M.Primitive` | `M.$Primitive` |\n| `M.Array`     | `M.$Array`     |\n| `M.Tuple`     | `M.$Tuple`     |\n| `M.Object`    | `M.$Object`    |\n| `M.Union`     | `M.$Union`     |\n| `M.Resolve`   | `M.$Resolve`   |\n| `M.Intersect` | `M.$Intersect` |\n| `M.Exclude`   | `M.$Exclude`   |\n","readmeFilename":"README.md","gitHead":"974a3e8db7db66566dac3de8b4a3dacaee350819","_id":"ts-algebra@1.1.0-beta.0","_nodeVersion":"16.6.2","_npmVersion":"7.20.3","dist":{"integrity":"sha512-YQ1AWVU4piEksMmdPz1+Zes2qrBr/2K172Lf9hcLYcgi3o7wqkD+gdyjTdjJw6hH5Lftbe0bWGXNkv1tDhQpAA==","shasum":"b71de986870de1899cad188d1d753f0fc859b74d","tarball":"http://registry-npm.ywwl.com/ts-algebra/download/ts-algebra-1.1.0-beta.0.tgz","fileCount":50,"unpackedSize":724835,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIEoRA4O2whBtNPCHbxJZIUWmDL8LquAjkni2AhoA8ByuAiEAiBQYFMTngh5aFd/NpM8hN1/479diZOzejiZCFaizgt4="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJibnbdACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmrYhA/8CsvDeG4irk/aB58cok6K913pnfitg4Tl+yC8XFx3Zqe6xcYl\r\nmXNeWqQfiIJ4uPILHjXKjoISZeAI+eXixJOKdGjLmRDmsE4zff9N9DFVLhnY\r\nnk5L8tZTE/Q2xqDlL2t7taXyQa7WVJ8+qZuX/yqHEhTSYpMrUjt8MR2N3Ecq\r\nzHuwjF4DNjeU2LChlEA6ZiL77GyyKQvZZaxSxXEBm7pidhnX1P3BmH0tyQN1\r\ntsWVYcwSBLYuEMcMQ5oTC2G4jrOzci6nsFHLbH0MjLe5kENiCziq8YHZiBoi\r\nnLIHRenMEhTSMFvu6aRaY5hzrSLjSdSwHSwRruDjVSZkcoh5+qAh2AQUeenW\r\nj2VgaWpCMlrk5uNjPLc1UlupJl0SQRQIjQUkjyGSOyLbb6RPPlPwriPFhtfh\r\n+1ZnGDwmPqx6lq0Kf5iP5rVKD5nB+6YFP5mrHbySKn2qc5Fd+rxq9rLd98YQ\r\nFS7CDSSB9rmGgIDbknH/r9VWXYVJqcw1Huc7cPngw/TqoQqPQXQiMWIbuSI1\r\nTPbXbw3CDVMJx5MY5sPJ524GkNLB+KGGwefHHXS6mOXQX47fk8MBWFZvAXnc\r\nx8IsA7Ej25YxEd/29b0T8wZRHIjHh9W9lbUbccNU0qipvMNMeQIQfV2/bgzh\r\nnJwdPcUziOOluuiQISTqMvuZTEJZ9ZYjNsY=\r\n=99cI\r\n-----END PGP SIGNATURE-----\r\n","size":541021,"noattachment":false,"key":"/ts-algebra/-/ts-algebra-1.1.0-beta.0.tgz"},"_npmUser":{"name":"thomasaribart","email":"thomas.aribart@gmail.com"},"directories":{},"maintainers":[{"name":"thomasaribart","email":"thomas.aribart@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-algebra_1.1.0-beta.0_1651406557085_0.5416294866692624"},"_hasShrinkwrap":false,"publish_time":1651406557341,"_cnpm_publish_time":1651406557341,"dist-tags":{"beta":"1.2.0-beta.0","latest":"2.0.0"}}