types-guards
v0.1.0
Published
Utilities for checking types in the typescript code.
Maintainers
Readme
types-guards
Small, focused utilities for runtime type checks and safe value coercions in TypeScript/JavaScript.
Features
- Lightweight guards:
isString,isNumber,isBoolean,isNull,isArray,isFunction,isUndefined,isNullish. - Empty checks:
isEmptyString,isEmptyArray. - Ensure helpers that coerce or return safe defaults:
ensureString,ensureNumber,ensureBoolean,ensureArray,ensureNull,ensureUndefined.
Table of Contents
Install
Install with your package manager of choice:
pnpm add types-guards
# or
npm install types-guards
# or
yarn add types-guardsQuick Usage
import { isString, isEmptyArray, ensureString, ensureArray } from 'types-guards'
if (isString(value)) {
// value is narrowed to string
}
const s = ensureString(maybeValue) // returns a string or ''
const arr = ensureArray(maybeList) // returns an array or []Utilities
Check types
| Function | Description |
| --------------- | ----------------------------------------------- |
| isString() | Determines whether a value is a string |
| isNumber() | Determines whether a value is a number |
| isBoolean() | Determines whether a value is a boolean |
| isNull() | Determines whether a value is null |
| isArray() | Determines whether a value is an array |
| isFunction() | Determines whether a value is a function |
| isUndefined() | Determines whether a value is undefined |
| isNullish() | Determines whether a value is undefined or null |
Check empty values
| Function | Description |
| ----------------- | --------------------------------------------- |
| isEmptyString() | Determines whether a value is an empty string |
| isEmptyArray() | Determines whether a value is an empty array |
Ensure values
| Function | Description |
| ------------------- | -------------------------------------------------------------------------------------------- |
| ensureString() | Determines whether a value is a string and returns it, otherwise returns an empty string |
| ensureBoolean() | Determines whether a value is a boolean and returns it, otherwise returns a false value |
| ensureNumber() | Determines whether a value is a number and returns it, otherwise returns a zero value |
| ensureUndefined() | Determines whether a value is undefined and returns it, otherwise returns an undefined value |
| ensureNull() | Determines whether a value is null and returns it, otherwise returns a null value |
| ensureArray() | Determines whether a value is an array and returns it, otherwise returns an empty array |
License
Copyright (c) 2024 Migudevelop
