Gathering detailed insights and metrics for ts-algebra
Gathering detailed insights and metrics for ts-algebra
Gathering detailed insights and metrics for ts-algebra
Gathering detailed insights and metrics for ts-algebra
npm install ts-algebra
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
19 Stars
73 Commits
2 Forks
3 Watching
1 Branches
1 Contributors
Updated on 15 Nov 2024
TypeScript (96.32%)
JavaScript (2.14%)
Shell (1.54%)
Cumulative downloads
Total Downloads
Last day
-11%
100,790
Compared to previous day
Last week
4.5%
587,369
Compared to previous week
Last month
15%
2,405,591
Compared to previous month
Last year
218%
21,859,127
Compared to previous year
22
💖 Huge thanks to the sponsors who help me maintain this repo:
ts-algebra
exposes a subset of TS types called Meta-types: Meta-types are types that encapsulate other types.
1import { Meta } from "ts-algebra"; 2 3type MetaString = Meta.Primitive<string>;
The encapsulated type can be retrieved using the Resolve
operation.
1type Resolved = Meta.Resolve<MetaString>; 2// => string 🙌
You can also use the more compact M
notation:
1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Primitive<string> 5>;
Meta-types allow operations that are not possible with conventional types.
For instance, they allow new "intersect" and "exclude" operations, and handling objects additional properties:
1type MyObject = { 2 str: string; // <= ❌ "str" is assignable to string 3 [key: string]: number; 4}; 5 6type MyObjectKeys = keyof MyObject; 7// => string <= ❌ Unable to isolate "str"
Think 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.
Meta-types were originally part of json-schema-to-ts. Check it to see a real-life usage.
1# npm 2npm install --save-dev ts-algebra 3 4# yarn 5yarn add --dev ts-algebra
A bit of theory first:
An important notion to keep in mind using ts-algebra
:
M.Never
is the only Meta-Type that is non-representable
(i.e. that resolves to never
)
Any other non-representable meta-type (e.g. an object with a non-representable but required property) will be instanciated as M.Never
.
There 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 and exclusions. This is crucial for performances and stability.
1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Never 5>; 6// => never
Arguments:
IsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Any 5>; 6// => unknown
Used for types with cardinalities of 1.
Arguments:
Value (type)
IsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Const<"I love pizza"> 5>; 6// => "I love pizza"
Used for types with finite cardinalities.
Arguments:
Values (type union)
IsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Food = M.Resolve< 4 M.Enum<"pizza" | "tacos" | "fries"> 5>; 6// => "pizza" | "tacos" | "fries"
☝️
M.Enum<never>
is non-representable
Used for either string
, number
, boolean
or null
.
Arguments:
Value (string | number | boolean | null)
IsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Primitive<string> 5>; 6// => string
Used for lists of items of the same type.
Arguments:
Items (?meta-type = M.Any)
IsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Array 5>; 6// => unknown[] 7 8type Resolved = M.Resolve< 9 M.Array<M.Primitive<string>> 10>; 11// => string[]
☝️ Any meta-array is representable by
[]
Used for finite, ordered lists of items of different types.
Meta-tuples can have additional items, typed as M.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.
Arguments:
RequiredItems (meta-type[]):
AdditionalItems (?meta-type = M.Never)
: Type of additional itemsIsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Tuple<[M.Primitive<string>]> 5>; 6// => [string] 7 8type Resolved = M.Resolve< 9 M.Tuple< 10 [M.Primitive<string>], 11 M.Primitive<string> 12 > 13>; 14// => [string, ...string[]]
☝️ A meta-tuple is non-representable if one of its required items is non-representable
Used for sets of key-value pairs (properties) which can be required or not.
Meta-objects can have additional properties, typed as M.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.
In 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 and exclusions).
Arguments:
NamedProperties (?{ [key:string]: meta-type } = {})
RequiredPropertiesKeys (?string union = never)
AdditionalProperties (?meta-type = M.Never)
: The type of additional propertiesCloseOnResolve (?boolean = false)
: Ignore AdditionalProperties
at resolution timeIsSerialized (?boolean = false)
: See deserializationDeserialized (?type = never)
: See deserialization1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Object< 5 { 6 required: M.Primitive<string>; 7 notRequired: M.Primitive<null>; 8 }, 9 "required", 10 M.Primitive<number> 11 > 12>; 13// => { 14// req: string, 15// notRequired?: null, 16// [key: string]: unknown 17// } 18 19type ClosedOnResolve = M.Resolve< 20 M.Object< 21 { 22 required: M.Primitive<string>; 23 notRequired: M.Primitive<null>; 24 }, 25 "required", 26 M.Primitive<number>, 27 false 28 > 29>; 30// => { 31// req: string, 32// notRequired?: null, 33// }
☝️ A meta-object is non-representable if one of its required properties value is non-representable:
- If it is a non-representable named property
- If it is an additional property, and the object is closed
Used to combine meta-types in a union of meta-types.
Arguments:
Values (meta-type union)
1import { M } from "ts-algebra"; 2 3type Food = M.Resolve< 4 M.Union< 5 | M.Primitive<number> 6 | M.Enum<"pizza" | "tacos" | "fries"> 7 | M.Const<true> 8 > 9>; 10// => number 11// | "pizza" | "tacos" | "fries" 12// | true
☝️ A meta-union is non-representable if it is empty, or if none of its elements is representable
☝️ Along with M.Never, M.Union is the only meta-type that doesn't support serialization
Resolves the meta-type to its encapsulated type.
Arguments:
MetaType (meta-type)
1import { M } from "ts-algebra"; 2 3type Resolved = M.Resolve< 4 M.Primitive<string> 5>; 6// => string
Takes two meta-types as arguments, and returns their intersection as a meta-type.
Arguments:
LeftMetaType (meta-type)
RightMetaType (meta-type)
1import { M } from "ts-algebra"; 2 3type Intersected = M.Intersect< 4 M.Primitive<string>, 5 M.Enum<"I love pizza" 6 | ["tacos"] 7 | { and: "fries" } 8 > 9> 10// => M.Enum<"I love pizza">
Meta-type intersections differ from conventional intersections:
1type ConventionalIntersection = 2 { str: string } & { num: number }; 3// => { str: string, num: number } 4 5type MetaIntersection = M.Intersect< 6 M.Object< 7 { str: M.Primitive<string> }, 8 "str" 9 >, 10 M.Object< 11 { num: M.Primitive<number> }, 12 "num" 13 > 14>; 15// => M.Never: "num" is required in B 16// ...but denied in A
Intersections are recursively propagated among tuple items and object properties, and take into account additional items and properties:
1type Intersected = M.Intersect< 2 M.Tuple< 3 [M.Primitive<number>], 4 M.Primitive<string> 5 >, 6 M.Tuple< 7 [M.Enum<"pizza" | 42>], 8 M.Enum<"fries" | true> 9 > 10>; 11// => M.Tuple< 12// [M.Enum<42>], 13// M.Enum<"fries"> 14// > 15 16type Intersected = M.Intersect< 17 M.Object< 18 { food: M.Primitive<string> }, 19 "food", 20 M.Any 21 >, 22 M.Object< 23 { age: M.Primitive<number> }, 24 "age", 25 M.Enum<"pizza" | "fries" | 42> 26 > 27>; 28// => M.Object< 29// { 30// food: M.Enum<"pizza" | "fries">, 31// age: M.Primitive<number> 32// }, 33// "food" | "age", 34// M.Enum<"pizza" | "fries" | 42> 35// >
Intersections are distributed among unions:
1type Intersected = M.Intersect< 2 M.Primitive<string>, 3 M.Union< 4 | M.Const<"pizza"> 5 | M.Const<42> 6 > 7>; 8// => M.Union< 9// | M.Const<"pizza"> 10// | M.Never 11// >
Takes two meta-types as arguments, and returns their exclusion as a meta-type.
Arguments:
SourceMetaType (meta-type)
ExcludedMetaType (meta-type)
1import { M } from "ts-algebra"; 2 3type Excluded = M.Exclude< 4 M.Enum<"I love pizza" 5 | ["tacos"] 6 | { and: "fries" } 7 >, 8 M.Primitive<string>, 9> 10// => M.Enum< 11// | ["tacos"] 12// | { and: "fries" } 13// >
Meta-type exclusions differ from conventional exclusions:
1type ConventionalExclusion = Exclude< 2 { req: string; notReq?: string }, 3 { req: string } 4>; 5// => never 6// ObjectA is assignable to ObjectB 7 8type MetaExclusion = M.Exclude< 9 M.Object< 10 { 11 req: M.Primitive<string>; 12 notReq: M.Primitive<string>; 13 }, 14 "req" 15 >, 16 M.Object< 17 { req: M.Primitive<string> }, 18 "req" 19 > 20>; 21// => ObjectA 22// Exclusion is still representable
1type ConventionalExclusion = Exclude< 2 { food: "pizza" | 42 }, 3 { [k: string]: number } 4>; 5// => { food: "pizza" | 42 } 6 7type MetaExclusion = M.Exclude< 8 M.Object< 9 { food: M.Enum<"pizza" | 42> }, 10 "food" 11 >, 12 M.Object< 13 {}, 14 never, 15 M.Primitive<number> 16 > 17>; 18// => M.Object< 19// { food: M.Enum<"pizza"> }, 20// "food" 21// >
When 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:
1type Excluded = M.Exclude< 2 M.Tuple<[M.Enum<"pizza" | 42>]>, 3 M.Tuple<[M.Primitive<number>]> 4>; 5// => M.Tuple<[M.Enum<"pizza">]> 6 7type Excluded = M.Exclude< 8 M.Tuple< 9 [M.Enum<"pizza" | 42>], 10 M.Enum<"fries" | true> 11 >, 12 M.Tuple< 13 [M.Primitive<number>], 14 M.Primitive<string> 15 > 16>; 17// => TupleA 18// Exclusion is not collapsable on a single item 19 20type Excluded = M.Exclude< 21 M.Object< 22 { 23 reqA: M.Enum<"pizza" | 42>; 24 reqB: M.Enum<"pizza" | 42>; 25 }, 26 "reqA" | "reqB" 27 >, 28 M.Object< 29 {}, 30 never, 31 M.Primitive<number> 32 > 33>; 34// => ObjectA 35// Exclusion is not collapsable on a single property
Exclusions are distributed among unions:
1type Excluded = M.Exclude< 2 M.Union< 3 | M.Const<"pizza"> 4 | M.Const<42> 5 >, 6 M.Primitive<number> 7>; 8// => M.Union< 9// | M.Const<"pizza"> 10// | M.Never 11// >
Excluding a union returns the intersection of the exclusions of all elements, applied separately:
1type Excluded = M.Exclude< 2 M.Enum<42 | "pizza" | true>, 3 M.Union< 4 | M.Primitive<number> 5 | M.Primitive<boolean> 6 > 7>; 8// => M.Enum<"pizza">
All meta-types except M.Never
and M.Union
can carry an extra type for deserialization purposes. This extra-type will be passed along in operations and override the resolved type.
For instance, it is common to deserialize timestamps as Date
objects. The last two arguments of M.Primitive
can be used to implement this:
1type MetaTimestamp = M.Primitive< 2 string, 3 true, // <= enables deserialization (false by default) 4 Date // <= overrides resolved type 5>; 6 7type Resolved = M.Resolve<MetaTimestamp>; 8// => Date
Note that MetaTimestamp
will still be considered as a string meta-type until it is resolved: Deserialization only take effect at resolution time.
1type Intersected = M.Intersect< 2 MetaTimestamp, 3 M.Object<{}, never, M.Any> // <= Date is an object... 4>; 5// => M.Never 6// ...but doesn't intersect Timestamp
In representable intersections:
A & B
).1type MetaBrandedString = M.Primitive< 2 string, 3 true, 4 { brand: "timestamp" } 5>; 6 7type Resolved = M.Resolve< 8 M.Intersect< 9 MetaTimestamp, 10 MetaBrandedString 11 > 12> 13// => Date & { brand: "timestamp" }
In representable exclusions:
To prevent errors, meta-types inputs are validated against type constraints:
1type Invalid = M.Array< 2 string // <= ❌ Meta-type expected 3>;
If you need to use them, all type constraints are also exported:
Meta-type | Type constraint |
---|---|
M.Any | M.AnyType = M.Any |
M.Never | M.NeverType = M.Never |
M.Const | M.ConstType = M.Const<any> |
M.Enum | M.EnumType = M.Enum<any> |
M.Primitive | M.PrimitiveType = M.Primitive<null | boolean | number | string> |
M.Array | M.ArrayType = M.Array<M.Type> |
M.Tuple | M.TupleType = M.Tuple<M.Type[], M.Type> |
M.Object | M.ObjectType = M.Object<Record<string, M.Type>, string, M.Type> |
M.Union | M.UnionType = M.Union<M.Type> |
- | M.Type = Union of the above |
In deep and self-referencing computations like in 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.
1type MyArray = M.Array< 2 VeryDeepTypeComputation< 3 ... 4 > // <= 💥 Type constraint can break 5>
For 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 😉
Safe | Unsafe |
---|---|
M.Any | - |
M.Never | - |
M.Const | - |
M.Enum | - |
M.Primitive | M.$Primitive |
M.Array | M.$Array |
M.Tuple | M.$Tuple |
M.Object | M.$Object |
M.Union | M.$Union |
M.Resolve | M.$Resolve |
M.Intersect | M.$Intersect |
M.Exclude | M.$Exclude |
No vulnerabilities found.
No security vulnerabilities found.