Libslm Guard is a TypeScript library that provides a set of guard clauses for validating data. It allows developers to write concise and expressive validation code, reducing boilerplate and improving readability. The library is designed to be extensible, enabling users to create custom guards for specific use cases.
⚠️ Use at your own risk.
ℹ️ This library is built with curiosity in mind. It's stable-ish, but don't use it in production unless you want to embrace the chaos.
- Built-in Guards: A variety of built-in guard methods for common validation scenarios.
- Custom Guards: Easily create custom guard methods to suit specific needs.
- Extensible: The library is designed to be extensible, allowing for future additions and improvements.
- TypeScript Support: Fully typed for better developer experience and type safety.
All Methods can be given custom error messages.
| Method | Description |
|---|---|
| guard.against.null | Throws if any of the provided variables are null. |
| guard.against.undefined | Throws if any of the provided variables are undefined. |
| guard.against.empty | Throws if any of the provided variables are empty (e.g., empty string, empty array). |
| guard.against.outOfRange | Throws if any of the provided variables are outside the specified range. |
| guard.against.less | Throws if any of the provided variables are less than the specified minimum. |
| guard.against.bigger | Throws if any of the provided variables are greater than the specified maximum. |
| guard.is.number | Throws if any of the provided variables are not numbers. |
| guard.is.string | Throws if any of the provided variables are not strings. |
| guard.is.boolean | Throws if any of the provided variables are not booleans. |
| guard.is.object | Throws if any of the provided variables are not objects. |
| guard.is.bigint | Throws if any of the provided variables are not bigints. |
| guard.is.symbol | Throws if any of the provided variables are not symbols. |
| guard.is.undefined | Throws if any of the provided variables are not undefined. |
| guard.is.null | Throws if any of the provided variables are not null. |
Here’s how the built-in guard clauses can be used:
import {guard} from 'libslm-guard';
function foo(value: unknown) {
guard.against.null({value}) // throws if value is null
guard.against.undefined({value}) // throws if value is undefined
guard.is.string({value}) // throws if value is not a string
console.info(typeof value) // string
guard.against.empty({value}, `guard.against.empty: '%variable' is empty.`) // throws if value is an empty string, with a custom error message
}- ✅ Basic implementation of concept
- 🔲 Better error handling and messaging
- 🔲 Add unit tests
- 🔲 More methods (maybe...)
Since this library is experimental, these implementations may change or expand over time. Use them as needed, tweak them as desired, and embrace the chaos.
- All of the guarding functions are written from scratch.
- You can help! Feel free to open issues or PRs.