@type-check/guards
v2026.1.16
Published
@type-check/guards provides high-performance, security-focused runtime type checks following current 2026 best practices. Built for professional TypeScript, Node.js, and modern browser environments, this package delivers precise and efficient type-guard f
Downloads
478
Maintainers
Keywords
Readme
@type-check/guards
Straightforward to use (one example):
import {isFloat} from "@type-check/guards";
isFloat(1337); // falseTable of contents: runtime type checks and guards
- What is @type-check/guards?
- Why should I use @type-check/guards?
- How to use @type-check/guards?
- Exported TypeScript types
- Functions / Methods
- @type-check ecosystem
- Contributing & Support
What is @type-check/guards?
@type-check/guards provides powerful, safety-oriented runtime type checks according to 2026 best practices, written in TypeScript by Roland Milto.
This package is designed for professional TypeScript, Node.js, and modern browser environments, offering precise and efficient type-checking functions with continuous development.
The module exports an object containing all type-checking functions while also providing tree-shakable exports for each function. Additionally, types within arrays can be validated.
Why should I use @type-check/guards?
Unlike heavy frameworks like Chai, Jest, or Vitest, which are primarily designed for isolated testing
environments, @type-check/guards was developed for maximum efficiency in production (runtime) and the highest
precision during design-time testing.
Browsersupport
@type-check/guardssupports all modern browsers, including Chrome, Edge, Firefox, Opera, and Safari.
Maximum performance and resource efficiency
Minimal footprint: Through consistent tree-shaking and zero dependencies, the bundle size remains minimal. This saves memory (RAM) and reduces loading times.
CPU optimization: The guards (such as
isOfType) internally use "fast-path" shortcuts for primitive types. This avoids unnecessary function calls and processing load, even with millions of validations per second.Simple syntax: No more complex assertion chains. A clear, functional API (e.g.,
isString(value)) ensures more readable code and faster development.
Runtime safety and design-time power
This package protects the application during execution from corrupt data while offering enormous benefits during development:
Strict Validation: JavaScript design flaws are natively corrected (e.g.,
typeof null === 'object'ortypeof NaN === 'number'). The guards check what you mean, not what JavaScript claims.Content Validation: While testing frameworks often only check if an array exists, functions like
areStringsorareIntegersefficiently validate the entire content – deep and secure.Intelligent Type Guards: Every function is a true TypeScript Type Guard. Once a check passes, TypeScript automatically recognizes the type in the following code block. This replaces unsafe type casting (
as string) with real logic.
// Without Guards:
function process(value: unknown) {
if (typeof value === 'string') {
(value as string).toUpperCase(); // Manual casting often required
}
}
// With @type-check/guards:
if (isString(value)) {
value.toUpperCase(); // TypeScript recognizes the type immediately
}Excellent for design-time testing
Although optimized for runtime, @type-check/guards is the perfect addition to your test suites:
- Use the same valid checking mechanisms in your unit tests as in your production logic.
- No complex configuration of tests is required – the guards work everywhere: Node.js, browser, edge runtimes, or serverless functions.
API consistency
To minimize errors during comparisons, @type-check/guards follows a strict camelCase strategy.
All strings returned by getTypeOf, as well as the type identifiers in isOfType, are consistently camelCase (e.g.,
"nan" instead of "NaN", "bigInt" instead of "BigInt").
How to use @type-check/guards?
Prerequisites
The package is designed as a native ES module (ESM) and supports all modern environments from ES2020+ (Node.js 16+, current browsers, and edge runtimes) to ensure maximum efficiency without unnecessary polyfills.
Installation
To install @type-check/guards, use the following command in your terminal:
npm install @type-check/guardspackage.json
Ensure that @type-check/guards is included in your package.json dependencies and always use the latest version:
{
"dependencies": {
"@type-check/guards": "*"
}
}tsconfig.json
Since @type-check/guards is exported as an ESM module, it is necessary to
adjust the moduleResolution option in the tsconfig.json file
to avoid error messages from the TypeScript compiler:
{
"compilerOptions": {
"moduleResolution": "NodeNext"
}
}Import
Local function imports
Individual import of specific functions (Tree-Shaking):
import {isInteger} from "@type-check/guards";
isInteger(1337); // trueLocal object import
Importing the type-check object:
import {type} from "@type-check/guards/as-object";
type.isInteger(42); // trueUsing a different name or alias:
import {type as values} from "@type-check/guards/as-object";
values.areIntegers([42, 1337]); // trueGlobal function imports
Use @type-check/guards as a global import for all functions, so you only need to include the libary once in your
project:
import '@type-check/guards/register-global';
isPlainObject({}); // trueIf your IDE does not automatically recognize the types, you can manually register them in tsconfig.json:
{
"compilerOptions": {
"types": [
"@type-check/guards/register-global"
]
}
}Browser import
If the bundle is to be hosted locally, the minified bundle can be found at dist/index.min.mjs in the package
directory.
For rapid prototyping or direct browser usage (without a build step), you can load @type-check/guards via the Delivery
Network (CDN) jsDelivr or unpkg:
<script type="module">
import {isFloat, areStrings} from 'https://cdn.jsdelivr.net/npm/@type-check/guards/dist/index.min.mjs';
console.log(isFloat(1337)); // false
console.log(areStrings(["TS", "JS"])); // true
</script>For unpkg use: https://unpkg.com/@type-check/guards/dist/index.min.mjs
Usage
All functions or methods take one argument and return a boolean value, except the functions or methods
isEqual, isOfType, isOneOfType, areEqual, areOfType, and areOneOfType, which take two arguments.
The first argument is always the value to be checked, the second argument is the expected type. For __OneOfType functions, the types must be provided in an array.
import {areStrings, getTypeOf, isBigInt, isInteger, isOfType} from "@type-check/guards";
console.log(getTypeOf(42)); // string 'number'
console.log(isOfType("Written by Roland Milto", "string")); // true
console.log(isInteger(42)); // true
console.log(isBigInt(42)); // false
console.log(areStrings(["Made", "by", "Roland", "Milto"])); // trueExamples
Example data
const user1 = {
id: 1337,
name: "Roland Milto",
email: "[email protected]",
isManager: true,
locations: [
"Berlin",
"Hamburg",
"Munich"
]
}Example with tree-shakable functions:
import {areStrings, isBoolean, isInteger, isPlainObject, isString} from "@type-check/guards";
function checkAccountDetails(options) {
if (!isPlainObject(options))
throw new TypeError("options must be a plain object");
if (!isInteger(options.id))
throw new TypeError("options.id must be an integer");
if (isString(options.name))
console.log("Account:", options.name ?? "No name provided");
if (isString(options.email))
console.log("Contact Email:", options.email ?? "No email provided");
console.log("Manager:", options.isManager ? "Yes" : "No");
// Arrays are supported:
if (areStrings(options.locations)) {
for (const location of options.locations) {
console.log("Location:", location);
}
}
}
checkAccountDetails(user1);Example with object export:
import {type} from "@type-check/guards/as-object";
function checkAccountDetails(options) {
if (!type.isPlainObject(options))
throw new TypeError("options must be a plain object");
if (!type.isInteger(options.id))
throw new TypeError("options.id must be an integer");
if (type.isString(options.name))
console.log("Account:", options.name ?? "No name provided");
if (type.isString(options.email))
console.log("Contact Email:", options.email ?? "No email provided");
console.log("Manager:", options.isManager ? "Yes" : "No");
// Also arrays are supported:
if (type.areStrings(options.locations)) {
for (const location of options.locations) {
console.log("Location:", location);
}
}
}
checkAccountDetails(user1);Exported TypeScript types
For seamless integration into your TypeScript projects, @type-check/guards exports helpful union types. You can use
these to type your own variables or ensure your logic only uses the type identifiers supported by this library.
Importing types
import type {DataType, Primitive, NonPrimitive, NumberType} from "@type-check/guards";DataType: The master union ofPrimitiveandNonPrimitive. It covers all identifiers that can be returned bygetTypeOf.Primitive: Includes all basic data types such asstring,number,boolean,bigInt,symbol,integer,float,nan,null, andundefined.NonPrimitive: Includes complex structures likearray,object,date,error,function,map,set,promise,regExp,stream",buffer,weakMap", andweakSet.NumericType: A specialized selection for numerical classifications (bigInt,binary,decimal,float,hexadecimal,integer,number, andoctal).
Functions / Methods
All functions are designed to provide precise results and can be used either via the type object or as an individual
import.
Type determination
getTypeOf(value) returns a string describing the type of the given value (always camelCase).
Type validations
All methods return a boolean value. The "Single Value Check" column checks an individual value, while the "Array Elements Check" column checks if every element in the provided array satisfies the condition.
| Single Value Check | Array Elements Check | |:-------------------------------------------------------------:|:---------------------------------------------------------------:| | isArray(value) | areArrays(array) | | isBigInt(value) | areBigInts(array) | | isBoolean(value) | areBooleans(array) | | isBuffer(value) | areBuffers(array) | | isDate(value) | areDates(array) | | isEqual(value, expected) | areEqual(value, expected) | | isError(value) | areErrors(value) | | isFalse(value) | areFalse(array) | | isFilledArray(value) | areFilledArrays(array) | | isFinite(value) | areFinite(array) | | isFloat(value) | areFloats(array) | | isFunction(value) | areFunctions(array) | | isInteger(value) | areIntegers(array) | | isMap(value) | areMaps(array) | | isNaN(value) | areNaNs(array) | | isNull(value) | areNull(array) | | isNullOrUndefined(value) | areNullOrUndefined(array) | | isNumber(value) | areNumbers(array) | | isObject(value) | areObjects(array) | | isOfType(value, type) | areOfType(array, type) | | isOneOfType(value, types[]) | areOneOfType(array, types[]) | | isPlainObject(value) | arePlainObjects(array) | | isPrimitive(value) | arePrimitives(array) | | isPromise(value) | arePromises(array) | | isRegEx(value) | areRegExes(array) | | isSet(value) | areSets(array) | | isStream(value) | areStreams(array) | | isString(value) | areStrings(array) | | isSymbol(value) | areSymbols(array) | | isTrue(value) | areTrue(array) | | isUndefined(value) | areUndefined(array) | | isValidDate(value) | areValidDates(array) | | isWeakMap(value) | areWeakMaps(array) | | isWeakSet(value) | areWeakSets(array) |
The @type-check ecosystem
@type-check/guards forms the foundation of a modular ecosystem, designed to ensure type safety at every stage of your
application. Due to the strict separation of modules, you only load the logic you actually need.
Available modules:
@type-check/assertions: Builds upon the guards and provides functions that immediately
throwan error if validation fails. Perfect for clean validation logic at the beginning of functions.Special feature: The module provides multilingual, configurable error messages that can be used directly in your application (e.g., for API responses or UI feedback). This eliminates the need to create your own error message texts.
@type-check/constraints: Enables the definition of complex rules and conditions (e.g., minimum string length, value ranges for numbers) that go beyond simple type checks.
Why strict separation?
Optimal performance: If you only need to check types, there is no need to load the code for complex assertions or constraints. This keeps the bundle tiny (CPU and RAM efficient).
Clear responsibilities: Each module has a specific task. This leads to more maintainable code and prevents API overload.
Maximum flexibility: You decide how strict your application should be – from simple boolean checks to hard assertions that stop the program flow upon errors.
Support or report an error
If you would also like to contribute to the library (e.g., translations), you are cordially invited to do so. Information can be found in CONTRIBUTING.md. You will also be mentioned in the AUTHORS.md file.
If you find any errors or have ideas for useful enhancements, you can contribute directly on GitHub.
