Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
type-detect
Advanced tools
The type-detect npm package is a utility for accurately detecting the types of JavaScript values. It goes beyond the basic `typeof` operator by being able to distinguish between more specific types, such as differentiating between an array and an object, or identifying specific types of objects like Date, RegExp, etc. This can be particularly useful in situations where strict type checking is necessary, such as input validation, or when working with complex data structures.
Detecting basic JavaScript types
This feature allows for the detection of basic JavaScript types such as number, boolean, string, null, and undefined. It provides a more reliable method than the `typeof` operator for these types.
"use strict";\nconst typeDetect = require('type-detect');\nconsole.log(typeDetect(1)); // 'number'\nconsole.log(typeDetect(true)); // 'boolean'\nconsole.log(typeDetect('Hello')); // 'string'\nconsole.log(typeDetect(null)); // 'null'\nconsole.log(typeDetect(undefined)); // 'undefined'
Distinguishing between arrays, objects, and null
This feature showcases the ability of type-detect to accurately distinguish between arrays, plain objects, and null, which is a common source of confusion when using the `typeof` operator.
"use strict";\nconst typeDetect = require('type-detect');\nconsole.log(typeDetect([])); // 'Array'\nconsole.log(typeDetect({})); // 'Object'\nconsole.log(typeDetect(null)); // 'null'
Identifying complex built-in types
This demonstrates type-detect's capability to identify more complex built-in JavaScript types such as Date objects and RegExp objects, which are not distinguishable using `typeof`.
"use strict";\nconst typeDetect = require('type-detect');\nconsole.log(typeDetect(new Date())); // 'Date'\nconsole.log(typeDetect(/regex/)); // 'RegExp'
The 'is' package provides a comprehensive set of type-check functions, similar to type-detect. It includes checks for primitive types, built-in objects, and also offers functions to test for specific conditions (like whether a number is integer). Compared to type-detect, 'is' might offer a more function-oriented approach for type checking.
The 'check-types' package offers a similar functionality to type-detect, focusing on providing a large set of assertion functions to validate the types of variables. It supports a wide range of types and conditions, including checks for truthy or falsy values. 'check-types' might be preferred in scenarios where assertions are more suitable than simple type detection.
Improved typeof detection for node, Deno, and the browser.
Supported Browsers | ||||
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | IE |
✅ | ✅ | ✅ | ✅ | 9, 10, 11 |
Type Detect is a module which you can use to detect the type of a given object. It returns a string representation of the object's type, either using typeof
or @@toStringTag
. It also normalizes some object names for consistency among browsers.
The typeof
operator will only specify primitive values; everything else is "object"
(including null
, arrays, regexps, etc). Many developers use Object.prototype.toString()
- which is a fine alternative and returns many more types (null returns [object Null]
, Arrays as [object Array]
, regexps as [object RegExp]
etc).
Sadly, Object.prototype.toString
is slow, and buggy. By slow - we mean it is slower than typeof
. By buggy - we mean that some values (like Promises, the global object, iterators, dataviews, a bunch of HTML elements) all report different things in different browsers.
type-detect
fixes all of the shortcomings with Object.prototype.toString
. We have extra code to speed up checks of JS and DOM objects, as much as 20-30x faster for some values. type-detect
also fixes any consistencies with these objects.
type-detect
is available on npm. To install it, type:
$ npm install type-detect
type-detect
can be imported with the following line:
import type from 'https://deno.land/x/type_detect@v4.1.0/index.ts'
You can also use it within the browser; install via npm and use the type-detect.js
file found within the download. For example:
<script src="./node_modules/type-detect/type-detect.js"></script>
The primary export of type-detect
is function that can serve as a replacement for typeof
. The results of this function will be more specific than that of native typeof
.
var type = require('type-detect');
Or, in the browser use case, after the
var type = typeDetect;
assert(type([]) === 'Array');
assert(type(new Array()) === 'Array');
assert(type(/a-z/gi) === 'RegExp');
assert(type(new RegExp('a-z')) === 'RegExp');
assert(type(function () {}) === 'function');
(function () {
assert(type(arguments) === 'Arguments');
})();
assert(type(new Date) === 'Date');
assert(type(1) === 'number');
assert(type(1.234) === 'number');
assert(type(-1) === 'number');
assert(type(-1.234) === 'number');
assert(type(Infinity) === 'number');
assert(type(NaN) === 'number');
assert(type(new Number(1)) === 'Number'); // note - the object version has a capital N
assert(type('hello world') === 'string');
assert(type(new String('hello')) === 'String'); // note - the object version has a capital S
assert(type(null) === 'null');
assert(type(undefined) !== 'null');
assert(type(undefined) === 'undefined');
assert(type(null) !== 'undefined');
var Noop = function () {};
assert(type({}) === 'Object');
assert(type(Noop) !== 'Object');
assert(type(new Noop) === 'Object');
assert(type(new Object) === 'Object');
All new ECMAScript 2015 objects are also supported, such as Promises and Symbols:
assert(type(new Map() === 'Map');
assert(type(new WeakMap()) === 'WeakMap');
assert(type(new Set()) === 'Set');
assert(type(new WeakSet()) === 'WeakSet');
assert(type(Symbol()) === 'symbol');
assert(type(new Promise(callback) === 'Promise');
assert(type(new Int8Array()) === 'Int8Array');
assert(type(new Uint8Array()) === 'Uint8Array');
assert(type(new UInt8ClampedArray()) === 'Uint8ClampedArray');
assert(type(new Int16Array()) === 'Int16Array');
assert(type(new Uint16Array()) === 'Uint16Array');
assert(type(new Int32Array()) === 'Int32Array');
assert(type(new UInt32Array()) === 'Uint32Array');
assert(type(new Float32Array()) === 'Float32Array');
assert(type(new Float64Array()) === 'Float64Array');
assert(type(new ArrayBuffer()) === 'ArrayBuffer');
assert(type(new DataView(arrayBuffer)) === 'DataView');
Also, if you use Symbol.toStringTag
to change an Objects return value of the toString()
Method, type()
will return this value, e.g:
var myObject = {};
myObject[Symbol.toStringTag] = 'myCustomType';
assert(type(myObject) === 'myCustomType');
FAQs
Improved typeof detection for node.js and the browser.
The npm package type-detect receives a total of 26,992,060 weekly downloads. As such, type-detect popularity was classified as popular.
We found that type-detect demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.