Equivalence
The Equivalence module provides a way to define equivalence relations between values in TypeScript. An equivalence relation is a binary relation that is reflexive, symmetric, and transitive, establishing a formal notion of when two values should be considered equivalent.
An Equivalence<A>
represents a function that compares two values of type A
and determines if they are equivalent. This is more flexible and customizable than simple equality checks using ===
.
Here’s the structure of an Equivalence
:
The module provides several built-in equivalence relations for common data types:
Equivalence | Description |
---|---|
string | Uses strict equality (=== ) for strings |
number | Uses strict equality (=== ) for numbers |
boolean | Uses strict equality (=== ) for booleans |
symbol | Uses strict equality (=== ) for symbols |
bigint | Uses strict equality (=== ) for bigints |
Date | Compares Date objects by their timestamps |
Example (Using Built-in Equivalences)
For more complex data structures, you may need custom equivalences. The Equivalence module lets you derive new Equivalence
instances from existing ones with the Equivalence.mapInput
function.
Example (Creating a Custom Equivalence for Objects)
The Equivalence.mapInput
function takes two arguments:
- The existing
Equivalence
you want to use as a base (Equivalence.number
in this case, for comparing numbers). - A function that extracts the value used for the equivalence check from your data structure (
(user: User) => user.id
in this case).