A lightweight JS utility for advanced type detection, validation, and enforcement.
- Determine the detailed type of any value (including distinguishing between integers and floats)
- Validate values against expected types with detailed error messages
- Check for common type categories like scalar, numeric, countable, infinite, etc.
- Supports multiple types (e.g.
int|float
) in validation - Works in browser and Node.js environments
Since TH is a self-contained script, you can include it directly in your project.
npm install typeh --save
Include the script in your HTML:
<script src="path/to/th.js"></script>
OR
// Node.js
require("typeh");
isA Types
- isCountable()
- isInteger()
- isDouble()
- isNumeric()
- isLong()
- isScalar()
- isInfinite()
- isString()
- isBool()
- isArray()
- isObject()
- isCallable()
- isIterable()
- isNull()
- isFalse()
- isTrue()
Type List
- int
- float
- string
- bool/boolean
- array
- object
- callable
- iterable
- mixed
- null
- false
- true
Others... Like (HTMLElement, regexp, symbol etc.) But support only in define
method.
Variable
// Required
const arr = array([]);
const str = string('Hello World');
const fn = callable(() => {});
const isBool = bool(true);
const num = int(12);
const float = float(12.22);
const values = iterable(new Set([1,2,3,4]));
const obj = object({});
const data = mixed("Foo"); // Allow all types
/* Optional/Required */
function myFun(username, email, number, isAdult) {
username = string(username); // [required]
email = _string(email); // [optional]
number = _int(number); // [optional]
isAdult = bool(isAdult); // [required]
}
myFun('Foo', null, null, true);
How to use custom Type
const custom = define("string|array|bool", []); // Allow (string, array, boolean) only
// Optional
const optval = define("?string|array"); // Allow (string, array, null, undefined)
Argument typeh
function select(selector, context, results, isSelf) {
setType({
string: selector, // [required]
HTMLElement: context, // [required]
array: results, // [required]
"?bool": isSelf // [optional]
});
}
How To Check Primitive Type
isType(/^[a-z]/); // Output: regexp
isType(new Date); // Output: date
isType('Hello'); // Output: string
isType(123); // Output: number
isType(true); // Output: boolean
isType(() => {}); // Output: function
isType([]); // Output: array
isType({}); // Output: object
isType(new Error()); // Output: error
isType(Symbol('Foo')); // Output: symbol
Check To Object Type
toType(12.21); // Output: float
toType(123); // Output: int
toType(/^[a-z]/); // Output: regexp
toType('Hello'); // Output: string
const body = document.body;
toType(body); // Output: HTMLBodyElement