Overview
@inzero/ts-uf is a collection of TypeScript utility functions.
Installation
npm install @inzero/ts-ufQuick Examples
import { isString } from "@inzero/ts-uf";
function foo(value: string | string[]) {
if (isString(value)) {
value; // string
} else {
value; // string[]
}
}Strictness
This library aims to provide utilities that are not too-strict and not too-loose.
Take isNonEmptyString() for example. If we made it too-strict by only allowing strings, then we won't be able
to use it on values of type unknown, any or values where string is a possible type:
const list = [1, "a", 2, "b"];
list.filter(isNonEmptyString); // Error
function foo(value: unknown) {
if (isNonEmptyString(value)) {
} // Error
}And if we made it too-loose by allowing anything, then we might end up checking a value that can never be a string, and no errors will be shown:
isNonEmptyString(1);
function foo(value: number) {
if (isNonEmptyString(value)) {
}
}So I chose the middle ground by allowing any value as long as using it makes sense.
const list = [1, "a", 2, "b"];
list.filter(isNonEmptyString); // string[]
isNonEmptyString(1); // errorNote: Since there's no straightforward way to tell TypeScript accept any type as long as it includes a certain type, I had to use some hacks that are hidden under an internal type. And since it's a hack don't expect it to be perfect. It works until proven otherwise 🙂
Before you continue
Throughout the documentation, you will notice that validation utilities have a parameter of type CheckT<T>:
function isNonEmptyString<T>(value: CheckT<T>): boolean;This is an internal type that checks whether a type include a certain type, a string in this case.
So passing a value that can never be a string will result in a TypeScript error. See Strictness Section for more details.
Notes
- The docs are automatically generated from the JSDoc comments in the source code.
- Each utility has "Shape" and "Source" tabs so you can see the expected parameters and return type, and how it's implemented.
Next
| Category | Suggested Utilities To Check |
|---|---|
| string | isString - isEmptyString - isBlank |
| number | isNumber |
| math | isInRange - doRangesOverlap - getRandomFloat - getRandomInteger - minmax - roundNumber |
| boolean | isBoolean |
| function | isFunction - iife |
| array | isArray - isEmptyArray - getRandomIndex - getRandomElement - mapOnDefined |
| object | isObject - hasKey - getDeep - setDeep |
| other | isEmpty - isOneOf - mapDefined - weightedRandom |