Skip to content

Commit

Permalink
Handle null in TypeScript optional
Browse files Browse the repository at this point in the history
  • Loading branch information
NolwennD committed Sep 19, 2024
1 parent 8b97ff3 commit 5418648
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/main/webapp/app/shared/optional/domain/Optional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ export abstract class Optional<Value> {
return new ValuatedOptional(value);
}

static ofUndefinable<Value>(value: Value | undefined): Optional<Value> {
if (value === undefined) {
return Optional.empty();
static ofUndefinable<Value>(value: Value | undefined | null): Optional<Value> {
if (value) {
return Optional.of(value);
}

return Optional.of(value);
return Optional.empty();
}

abstract map<Output>(mapper: (value: Value) => Output): Optional<Output>;
Expand Down
4 changes: 4 additions & 0 deletions src/test/webapp/unit/shared/optional/domain/Optional.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ describe('Optional', () => {
expect(Optional.ofUndefinable(undefined).isEmpty()).toBe(true);
});

it('should get empty optional from null value', () => {
expect(Optional.ofUndefinable(null).isEmpty()).toBe(true);
});

it('should get valuated optional from actual value', () => {
expect(Optional.ofUndefinable('toto').isEmpty()).toBe(false);
});
Expand Down

0 comments on commit 5418648

Please sign in to comment.