functional/typing.ts

37 lines
901 B
TypeScript

import { pipe } from "./composition.ts";
/**
* Get a function to check that inputs are instances of a given type
*/
export function isinstance<T, S extends T>(
ref: { new (...args: any[]): T },
): (input: S) => input is Extract<T, S> {
return (x): x is Extract<T, S> => x instanceof ref;
}
/**
* Check that a value is not null, throwing an error if it is
*/
export function nn<T>(value: T | null): T {
if (value === null) {
throw new Error("null value");
} else {
return value;
}
}
/**
* Check that a value is not undefined, throwing an error if it is
*/
export function nu<T>(value: T | undefined): T {
if (typeof value === "undefined") {
throw new Error("undefined value");
} else {
return value;
}
}
/**
* Check that a value is not null nor undefined, throwing an error if it is
*/
export const nnu: <T>(value: T | null | undefined) => T = pipe(nn, nu);