unsplash / sum-types

Safe, ergonomic, non-generic sum types in TypeScript.
https://unsplash.github.io/sum-types/
MIT License
42 stars 2 forks source link

Members are not value-equal after serialize then deserialize #52

Closed OliverJAsh closed 1 year ago

OliverJAsh commented 1 year ago

Related to https://github.com/unsplash/sum-types/issues/35.

This test fails:

diff --git a/test/unit/index.ts b/test/unit/index.ts
index 142de4b..b4ed45f 100644
--- a/test/unit/index.ts
+++ b/test/unit/index.ts
@@ -29,6 +29,9 @@ describe("index", () => {
         expect(Weather.mk.Sun).not.toEqual(Weather.mk.Rain(123))
         expect(Weather.mk.Rain(123)).toEqual(Weather.mk.Rain(123))
         expect(Weather.mk.Rain(123)).not.toEqual(Weather.mk.Rain(456))
+
+        const x = Weather.mk.Sun
+        expect(deserialize<Weather>()(serialize(x))).toEqual(x)
       })
     })
    Expected: [Function nonNullary]
    Received: {Symbol(@unsplash/sum-types internal tag key): "Sun", Symbol(@unsplash/sum-types internal value key): null}

      32 |
      33 |         const x = Weather.mk.Sun
    > 34 |         expect(deserialize<Weather>()(serialize(x))).toEqual(x)
         |                                                      ^
      35 |       })
      36 |     })
samhh commented 1 year ago

Looks similarly fixable by taking the Sum instance as an argument in deserialize:

- deserialize<Weather>()
+ deserialize(Weather)
samhh commented 1 year ago

A drop-in test case:

diff --git a/test/unit/index.ts b/test/unit/index.ts
index 142de4b..4be69d9 100644
--- a/test/unit/index.ts
+++ b/test/unit/index.ts
@@ -74,5 +74,16 @@ describe("index", () => {
         }),
       )
     })
+
+    it('deserializations are reference-equal', () => {
+      type Weather = Member<"Sun"> | Member<"Rain", 123>
+      const Weather = create<Weather>()
+
+      const sun = Weather.mk.Sun
+      expect(deserialize<Weather>()(serialize(sun))).toEqual(sun)
+
+      const rain = Weather.mk.Rain(123)
+      expect(deserialize<Weather>()(serialize(rain))).toEqual(rain)
+    })
   })
 })

As expected, sun fails but rain succeeds. (They should both succeed.)