{"name":"ts-algebra","version":"1.0.0-beta.1","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.Any`](#any) by default).\n\n**Arguments:**\n\n- <code>RequiredItems <i>(meta-type[])</i>:</code>\n- <code>IsOpen <i>(?boolean = false)</i>:</code> Wether the tuple allows\n  additional items\n- <code>AdditionalItems <i>(?meta-type = M.Any)</i>:</code> Type of\n  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    true\n  >\n>;\n// => [string, ...unknown[]]\n\ntype Resolved = M.Resolve<\n  M.Tuple<\n    [M.Primitive<string>],\n    true,\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.Any`](#any) by default).\n\nIn presence of named properties, 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>IsOpen <i>(?boolean = false)</i>:</code> Wether the object allows\n  additional properties\n- <code>AdditionalProperties <i>(?meta-type = M.Any)</i>:</code> The type of\n  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    true,\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 doesn't allow it\n> - If it is an additional property, and additional properties are non-representable\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    true,\n    M.Primitive<string>\n  >,\n  M.Tuple<\n    [M.Enum<\"pizza\" | 42>],\n    true,\n    M.Enum<\"fries\" | true>\n  >\n>;\n// => M.Tuple<\n//  [M.Enum<42>],\n//  true,\n//  M.Enum<\"fries\">\n// >\n\ntype Intersected = M.Intersect<\n  M.Object<\n    { food: M.Primitive<string> },\n    \"food\",\n    true\n  >,\n  M.Object<\n    { age: M.Primitive<number> },\n    \"age\",\n    true,\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//  true,\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    true,\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    true,\n    M.Enum<\"fries\" | true>\n  >,\n  M.Tuple<\n    [M.Primitive<number>],\n    true,\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    true,\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[], boolean, M.Type>`                         |\n| `M.Object`    | `M.ObjectType` = `M.Object<Record<string, M.Type>, string, boolean, 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":"3e6e1843bf241babd7bbc64f9bb7b4522c6769d5","_id":"ts-algebra@1.0.0-beta.1","_nodeVersion":"14.17.1","_npmVersion":"8.6.0","dist":{"integrity":"sha512-BKLiIVDHm0BWRssJ3J9ox/ibPzbQ73jW5JfoWLQ9PBPUiQdIcS6QYViN7jEPSFXdflcPnfZeL0cfUAuH+0oeCw==","shasum":"966cf8d1fae8807043830f1d86244c5dc832ecf4","tarball":"http://registry-npm.ywwl.com/ts-algebra/download/ts-algebra-1.0.0-beta.1.tgz","fileCount":48,"unpackedSize":717506,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDLB5EFjP9pITKPz4CYLkdjEGwiUtRUf56tC3Qvn2zDnAIhAOHz/3WKCmKUwNQLrORWwPt+9OOS/nBoN7OV5+J3wBmx"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiTahoACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmrCzw//Zmge0H1o9Fy7h3rMr7s5OyNz8dpBXGun/+dZKagbRlRDMNUV\r\nafTDaB+3w+EP7tYLKsRSUli8pXveyLIXRbCzEW3EbprjPo/kFcS2TcGZwsHJ\r\nv+DdrI0TxZFjUhJIiWIa5sgqABwvOHZfcfe+ktR4uzYvyNJt4mnIBHVaq/JO\r\nonitJADom0GIWZ/qkrVl+GytwTB5/DLvFtzQxb/JXzBOncpNzqD22NRVWzok\r\nktOSdExlSNkpDBwlqyjfeVn3wcoTcD623jFsXJMi8yTeLt4qdaENM0QZvNTd\r\n9G4yznco0JrK6DhAt0GE1ZaHdJqFGWSqRtWKMvnlrPdikSSwedORWB2luo95\r\nlIyD5Zb2XpHya/1s0uIxtSPbDBNXa3s+4Z9RWmB8Lc29GOYQfFSUUly7xcd1\r\ncG65QrYbBChWLinP/KnLUOf91nfSmHPtjBkrRnESVOswhbWD4NavIVhbfbbY\r\n9QENMVQlUpXY+sqdSqbEFmI0EleTxLXOLT/o60cqfpfySU33c3KMQ6kfXzOm\r\n8Sy4svaz5RSXb3rjbiG3oFhfcgW3KCQ/RuMj8QfGM9/T9kJpIIrIoMJrRuH1\r\nAOS5TOWiIC24VTJZD3dxP6GxYM2ikDvEpcCfPcphSjRPdHoQEYOYVrnUSquD\r\nkdSM68TYjcRYL3xt6IMsDvzMMp8UkxwfkvY=\r\n=uF8Y\r\n-----END PGP SIGNATURE-----\r\n","size":540249,"noattachment":false,"key":"/ts-algebra/-/ts-algebra-1.0.0-beta.1.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.0.0-beta.1_1649256552402_0.49914840195000365"},"_hasShrinkwrap":false,"publish_time":1649256552634,"_cnpm_publish_time":1649256552634,"dist-tags":{"beta":"1.2.0-beta.0","latest":"2.0.0"}}