A precise typechecker for JavaScript
kind() returns a useful name for a variable's type. It breaks down objects into more precise terms: array, null, element, etc.
Examples:
| Input | typeof | kind |
|---|---|---|
[1, 2, 3] |
"object" |
"array" |
null |
"object" |
"null" |
new Promise(() => null) |
"object" |
"promise" |
document.getElementById('id') |
"object" |
"element" |
document.getElementsByTagName('div') |
"object" |
"nodelist" |
document.createTextNode('') |
"object" |
"node" |
new Date() |
"object" |
"date" |
{} |
"object" |
"object" (if no special type was detected — see full list below) |
yarn: yarn add kindjs
npm: npm install kindjs
import kind from 'kindjs';
kind(['hello', 'world']);
//=> 'array'// Objects that aren't *really* objects
kind(null); // "null"
kind([1, 2, 3]); // "array"
kind(arguments); // "arraylike"
kind(new Date()); // "date"
kind(document.getElementById('id')); // "element"
kind(document.getElementsByTagName('div')); // "nodelist"
// This one's actually just an object
kind({}); // "object"
// Also works on standard types
kind("text"); // "string"
kind(2); // "number"
kind(alert); // "function"You may add a second, boolean parameter to tell kind to perform a deeper test for some types. For example, instead of "number" it could return "integer" or "float".
kind(1); // "number"
kind(1, true); // "integer"
kind(1.21); // "number"
kind(1.21, true); // "float"
kind(evt); // "event"
kind(evt, true); // "mouseevent" (i.e. if the event was a click)A complete list is noted below
- All standard types normally returned by
typeof:function,undefined,boolean,symbolstring- Deep option returns either
stringoremptystring
- Deep option returns either
number- Deep option returns either
integerorfloat
- Deep option returns either
arrayarraylike- A non-array object with a
.lengthproperty
- A non-array object with a
nullelementnode- Deep options from this list (e.g.
text,comment)
- Deep options from this list (e.g.
nodelistevent- Deep options from this list (e.g.
mouseevent,keyboardevent)
- Deep options from this list (e.g.
regexpdateerrorerroreventmathpromiseseturl(i.e. an instance of theURL()constructor)urlsearchparamsmap
- Works with any type, not just objects
- Always returns a simple lowercase string, just like the native
typeof - TypeScript support
- Handles undefined or undeclared variables
- Optimized to check for the most common types first
- Excellent browser support, including many very old browsers
- IE 6+ (and maybe older)
- Chrome
- Firefox
- Safari
- Android 1+
- Opera (pre-Blink)
- Netscape 4 (in theory!)
- Probably anything that runs JavaScript and supports regular expressions