diff --git a/src/index.ts b/src/index.ts index e174bdd..fdf94d6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -256,13 +256,12 @@ const mkMatchXW = (x: A): C => { const tag = x[tagKey] as Tag - const g = fs[tag] // eslint-disable-next-line functional/no-conditional-statement, @typescript-eslint/no-unsafe-return - if (g !== undefined) return g as C + if (Object.prototype.hasOwnProperty.call(fs, tag)) return fs[tag] as C - const h = (fs as CasesXWildcard)[_] // eslint-disable-next-line functional/no-conditional-statement, @typescript-eslint/no-unsafe-return - if (h !== undefined) return h as C + if (Object.prototype.hasOwnProperty.call(fs, _)) + return (fs as CasesXWildcard)[_] as C // eslint-disable-next-line functional/no-throw-statement throw new Error(`Failed to pattern match against tag "${tag}".`) diff --git a/test/unit/index.ts b/test/unit/index.ts index 5a531a8..2e6182a 100644 --- a/test/unit/index.ts +++ b/test/unit/index.ts @@ -84,6 +84,22 @@ describe("index", () => { expect(f(Weather.mk.Sun)).toBe("didn't rain") }) + it("matchX allow undefined value", () => { + type T = Member<"A"> | Member<"B"> | Member<"toString"> + const T = create() + + const f = T.matchX({ + A: undefined, + [_]: undefined, + }) + + expect(f(T.mk.A)).toBe(undefined) + expect(f(T.mk.B)).toBe(undefined) + // Check that `toString` does not match an object prototype function + // This check would fail when the `in` operator is used instead of `hasOwnProperty`. + expect(f(T.mk.toString)).toBe(undefined) + }) + it("matchXW", () => { const f = Weather.matchXW({ Rain: "rained", @@ -98,6 +114,22 @@ describe("index", () => { expect(f(Weather.mk.Sun)).toBeNull() }) + + it("matchXW allow undefined value", () => { + type T = Member<"A"> | Member<"B"> | Member<"toString"> + const T = create() + + const f = T.matchXW({ + A: undefined, + [_]: undefined, + }) + + expect(f(T.mk.A)).toBe(undefined) + expect(f(T.mk.B)).toBe(undefined) + // Check that `toString` does not match an object prototype function. + // This check would fail when the `in` operator is used instead of `hasOwnProperty`. + expect(f(T.mk.toString)).toBe(undefined) + }) }) })