|
| 1 | +import type { Err, Ok, Result } from 'neverthrow'; |
| 2 | +import type { UnknownRecord } from 'type-fest'; |
| 3 | +import { InvariantError } from './invariant'; |
| 4 | + |
| 5 | +function isObject(value: unknown): value is UnknownRecord { |
| 6 | + const type = typeof value; |
| 7 | + return value != null && (type === 'object' || type === 'function'); |
| 8 | +} |
| 9 | + |
| 10 | +export function assertError(error: unknown): asserts error is Error { |
| 11 | + // why not `error instanceof Error`? see https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1099 |
| 12 | + // biome-ignore lint/suspicious/noPrototypeBuiltins: safe |
| 13 | + if (!isObject(error) || !Error.prototype.isPrototypeOf(error)) { |
| 14 | + throw error; |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Exhaustiveness checking for union and enum types |
| 20 | + * see https://www.typescriptlang.org/docs/handbook/2/narrowing.html#exhaustiveness-checking |
| 21 | + */ |
| 22 | +export function assertNever( |
| 23 | + x: never, |
| 24 | + message = `Unexpected object: ${String(x)}`, |
| 25 | +): never { |
| 26 | + throw new InvariantError(message); |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Asserts that the given `Result<T, E>` is an `Ok<T, never>` variant. |
| 31 | + */ |
| 32 | +export function assertOk<T, E extends Error>( |
| 33 | + result: Result<T, E>, |
| 34 | +): asserts result is Ok<T, E> { |
| 35 | + if (result.isErr()) { |
| 36 | + throw new InvariantError( |
| 37 | + `Expected result to be Ok: ${result.error.message}`, |
| 38 | + ); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Asserts that the given `Result<T, E>` is an `Err<never, E>` variant. |
| 44 | + */ |
| 45 | +export function assertErr<T, E extends Error>( |
| 46 | + result: Result<T, E>, |
| 47 | +): asserts result is Err<T, E> { |
| 48 | + if (result.isOk()) { |
| 49 | + throw new InvariantError(`Expected result to be Err: ${result.value}`); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Asserts that the given value is not `null`. |
| 55 | + */ |
| 56 | +export function assertNotNull<T>(value: T): asserts value is Exclude<T, null> { |
| 57 | + if (value === null) { |
| 58 | + throw new InvariantError('Expected value to be not null'); |
| 59 | + } |
| 60 | +} |
0 commit comments