Skip to content

Commit

Permalink
fix: require Maybe#getOr callback to return the same type
Browse files Browse the repository at this point in the history
  • Loading branch information
faergeek committed Feb 8, 2024
1 parent 815c75c commit e6f7598
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
15 changes: 5 additions & 10 deletions src/maybe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,12 @@ describe('Maybe', () => {
expectTypeOf(someValue).toEqualTypeOf<number>();
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<number>();
expect(noneValue).toBe(42);

expectTypeOf(someObject).toEqualTypeOf<{ foo?: 'bar' }>();
expect(someObject).toBe(42);
});

it('#toNullable', () => {
Expand Down
12 changes: 9 additions & 3 deletions src/maybe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class Maybe<T> {
/**
* Return either a boxed value or a value return by `d` if there is none
*/
getOr<U>(d: () => T | U) {
getOr(d: () => T) {
return this.match({
Some: value => value,
None: d,
Expand All @@ -93,14 +93,20 @@ export class Maybe<T> {
* 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,
});
}

/**
Expand Down

0 comments on commit e6f7598

Please sign in to comment.