From e6f7598fd8bd7717584129b42b20e23fa01e7755 Mon Sep 17 00:00:00 2001 From: Sergey Slipchenko Date: Thu, 8 Feb 2024 22:00:39 +0400 Subject: [PATCH] fix: require Maybe#getOr callback to return the same type --- src/maybe.spec.ts | 15 +++++---------- src/maybe.ts | 12 +++++++++--- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/maybe.spec.ts b/src/maybe.spec.ts index 35c4abb..4c49ed0 100644 --- a/src/maybe.spec.ts +++ b/src/maybe.spec.ts @@ -58,17 +58,12 @@ describe('Maybe', () => { expectTypeOf(someValue).toEqualTypeOf(); expect(someValue).toBe(42); - const someValueWithDifferentFallbackType = Maybe.Some(42).getOr( - () => 'nothing', + const someObject = Maybe.Some<{ foo?: 'bar' }>({ foo: 'bar' }).getOr( + () => ({}), ); - expectTypeOf(someValueWithDifferentFallbackType).toEqualTypeOf< - number | string - >(); - expect(someValueWithDifferentFallbackType).toBe(42); - - const noneValue = Maybe.None.getOr(() => 42); - expectTypeOf(noneValue).toEqualTypeOf(); - expect(noneValue).toBe(42); + + expectTypeOf(someObject).toEqualTypeOf<{ foo?: 'bar' }>(); + expect(someObject).toBe(42); }); it('#toNullable', () => { diff --git a/src/maybe.ts b/src/maybe.ts index 6a49e79..4c17d5d 100644 --- a/src/maybe.ts +++ b/src/maybe.ts @@ -82,7 +82,7 @@ export class Maybe { /** * Return either a boxed value or a value return by `d` if there is none */ - getOr(d: () => T | U) { + getOr(d: () => T) { return this.match({ Some: value => value, None: d, @@ -93,14 +93,20 @@ export class Maybe { * Return either a boxed value or `null` if there is none */ toNullable() { - return this.getOr(() => null); + return this.match({ + None: () => null, + Some: value => value, + }); } /** * Return either a boxed value or `undefined` if there is none */ toOptional() { - return this.getOr(() => undefined); + return this.match({ + None: () => null, + Some: value => value, + }); } /**