is-array-of-type
v1.0.0
Published
Validate that all elements in an array are of a specific type
Maintainers
Readme
is-array-of
A lightweight JavaScript library to validate that all elements in an array are of a specific type.
Installation
npm install is-array-ofUsage
const isArrayOf = require('is-array-of');
// Validate primitive types using strings
isArrayOf([1, 2, 3], 'number'); // true
isArrayOf(['a', 'b', 'c'], 'string'); // true
isArrayOf([true, false], 'boolean'); // true
isArrayOf([1, '2', 3], 'number'); // false
// Validate arrays
isArrayOf([[1], [2], [3]], 'array'); // true
// Validate objects
isArrayOf([{}, {a: 1}], 'object'); // true
// Validate using constructor functions
class Person {
constructor(name) {
this.name = name;
}
}
const people = [new Person('John'), new Person('Jane')];
isArrayOf(people, Person); // true
// Built-in constructors
isArrayOf([new Date(), new Date()], Date); // true
isArrayOf([/test/, /regex/], RegExp); // true
// Empty arrays return true
isArrayOf([], 'string'); // true
// Non-arrays return false
isArrayOf('not an array', 'string'); // false
isArrayOf(null, 'string'); // falseAPI
isArrayOf(arr, type)
Parameters
arr(Array): The array to validatetype(string | Function): The type to check against- String values:
'string','number','boolean','function','object','array','null','undefined' - Constructor functions: Any constructor function (e.g.,
Date,RegExp, custom classes)
- String values:
Returns
boolean: Returnstrueif all elements match the specified type,falseotherwise
Features
- ✅ Supports primitive type validation (string, number, boolean, etc.)
- ✅ Supports constructor function validation (Date, RegExp, custom classes)
- ✅ Handles edge cases (empty arrays, null, undefined)
- ✅ Zero dependencies
- ✅ TypeScript definitions included
- ✅ Lightweight and fast
License
MIT
