Add assertion utilities

This commit is contained in:
Liam 2024-03-17 16:12:50 -04:00
parent 3cc9e90ff2
commit a608ff4af8
2 changed files with 63 additions and 0 deletions

View file

@ -0,0 +1,35 @@
import { assertNotNull, assertNotUndefined, assertType } from '../assert';
describe('Assertion utilities', () => {
describe('assertNotNull', () => {
it('should return non-null values', () => {
expect(assertNotNull(1)).toEqual(1);
expect(assertNotNull('anything')).toEqual('anything');
});
it('should throw when passed a null value', () => {
expect(() => assertNotNull(null)).toThrow('Expected non-null value');
});
});
describe('assertNotUndefined', () => {
it('should return non-undefined values', () => {
expect(assertNotUndefined(1)).toEqual(1);
expect(assertNotUndefined('anything')).toEqual('anything');
});
it('should throw when passed an undefined value', () => {
expect(() => assertNotUndefined(undefined)).toThrow('Expected non-undefined value');
});
});
describe('assertType', () => {
it('should return values of the generic type', () => {
expect(assertType({}, Object)).toEqual({});
});
it('should throw when passed a value of the wrong type', () => {
expect(() => assertType('anything', Number)).toThrow('Expected value of type');
});
});
});

28
assets/js/utils/assert.ts Normal file
View file

@ -0,0 +1,28 @@
export function assertNotNull<T>(value: T | null): T {
if (value === null) {
throw new Error('Expected non-null value');
}
return value;
}
export function assertNotUndefined<T>(value: T | undefined): T {
// eslint-disable-next-line no-undefined
if (value === undefined) {
throw new Error('Expected non-undefined value');
}
return value;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
type Constructor<T> = { new (...args: any[]): T };
export function assertType<T>(value: any, c: Constructor<T>): T {
if (value instanceof c) {
return value;
}
throw new Error('Expected value of type');
}
/* eslint-enable @typescript-eslint/no-explicit-any */