Skip to content

Commit

Permalink
feat: creating assertAndGetNonNullish
Browse files Browse the repository at this point in the history
  • Loading branch information
Farenheith committed Oct 7, 2024
1 parent 51f5fe6 commit 83186f0
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/asserts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ export function assert<T, R extends T>(
if (!check(v)) throwError(errorCallOrMessage ?? 'invalid type');
}

export function assertAndGet<T, R extends T>(
v: T,
check: (x: T) => x is R,
errorCallOrMessage?: AssertError,
): R {
assert(v, check, errorCallOrMessage);
return v;
}

export function assertNot<T, R extends T>(
v: T,
check: (x: T) => x is R,
Expand Down
5 changes: 4 additions & 1 deletion src/getters.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { assertAndGetProperty } from './asserts';
import { assertAndGet, assertAndGetProperty } from './asserts';
import { isNonNullish, isString } from './guards';
import { KeysOfType, Nullable, ObjectKeyType } from './types';

export function assertAndGetNonNullish<T>(value: Nullable<T>): NonNullable<T> {
return assertAndGet(value, isNonNullish);
}
export function getDefinedProperty<T extends object, K extends keyof T>(
obj: T,
prop: K,
Expand Down
38 changes: 37 additions & 1 deletion test/unit/getters.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { assertAndGetStringProperty, getDefinedProperty } from '../../src';
import {
assertAndGetNonNullish,
assertAndGetStringProperty,
getDefinedProperty,
} from '../../src';

describe('getters.ts', () => {
describe(getDefinedProperty.name, () => {
Expand Down Expand Up @@ -40,4 +44,36 @@ describe('getters.ts', () => {
expect(thrownError).toBeDefined();
});
});

describe(assertAndGetNonNullish.name, () => {
it('should return value when non nullish', () => {
const result = assertAndGetNonNullish('abc');

expect(result).toBe('abc');
});

it('should throw an error when informed value is null', () => {
let thrownError: any;

try {
assertAndGetNonNullish(null);
} catch (err) {
thrownError = err;
}

expect(thrownError).toBeDefined();
});

it('should throw an error when informed value is undefined', () => {
let thrownError: any;

try {
assertAndGetNonNullish(undefined);
} catch (err) {
thrownError = err;
}

expect(thrownError).toBeDefined();
});
});
});

0 comments on commit 83186f0

Please sign in to comment.