or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-type-detect

Improved typeof detection for node.js and the browser.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/type-detect@4.1.x

To install, run

npx @tessl/cli install tessl/npm-type-detect@4.1.0

index.mddocs/

Type Detect

Type Detect is an improved typeof detection library for Node.js, Deno, and browsers. It provides more specific type detection than JavaScript's native typeof operator, normalizing behavior across different engines and offering detailed type information for objects, arrays, and modern ECMAScript types.

Package Information

  • Package Name: type-detect
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install type-detect

Core Imports

import typeDetect from "type-detect";

For CommonJS:

const typeDetect = require("type-detect");

For Deno:

import typeDetect from "https://deno.land/x/type_detect@v4.1.0/index.ts";

For browsers (UMD):

<script src="./node_modules/type-detect/type-detect.js"></script>
<script>
  var typeDetect = typeDetect; // Available globally
</script>

Basic Usage

import typeDetect from "type-detect";

// Basic types
console.log(typeDetect("hello"));        // "string"
console.log(typeDetect(42));            // "number"
console.log(typeDetect(true));          // "boolean"
console.log(typeDetect(null));          // "null"
console.log(typeDetect(undefined));     // "undefined"

// Objects and arrays
console.log(typeDetect([]));            // "Array"
console.log(typeDetect({}));            // "Object"
console.log(typeDetect(/regex/));       // "RegExp"
console.log(typeDetect(new Date()));    // "Date"

// ES6+ types
console.log(typeDetect(new Map()));     // "Map"
console.log(typeDetect(new Set()));     // "Set"
console.log(typeDetect(Symbol()));      // "symbol"
console.log(typeDetect(Promise.resolve())); // "Promise"

// Typed arrays
console.log(typeDetect(new Int32Array())); // "Int32Array"
console.log(typeDetect(new Float64Array())); // "Float64Array"

// Browser DOM elements (when available)
if (typeof document !== 'undefined') {
  console.log(typeDetect(document)); // "Document"
  console.log(typeDetect(document.createElement('div'))); // "HTMLDivElement"
}

Architecture

Type Detect uses a carefully optimized algorithm that:

  • Performance First: Specialized checks that are 20-30x faster than Object.prototype.toString for certain values
  • Cross-Platform: Normalizes behavior across Node.js, Deno, and different browser engines
  • Modern Types: Full support for ES6+ types, iterators, and typed arrays
  • Browser DOM: Special handling for DOM elements and browser-specific objects
  • Zero Dependencies: No runtime dependencies for minimal footprint

Capabilities

Enhanced Type Detection

The core type detection functionality that serves as a drop-in replacement for JavaScript's typeof operator with enhanced specificity and cross-platform consistency.

function typeDetect(obj: unknown): string;

Parameters:

  • obj (unknown): The value to analyze for type detection

Returns:

  • string: A string representing the detected type

Supported Return Types:

Primitive Types

  • "string" - String literals
  • "number" - Number literals (including Infinity, NaN)
  • "boolean" - Boolean literals
  • "undefined" - Undefined values
  • "function" - Function objects
  • "symbol" - Symbol values

Object Types

  • "null" - Null values
  • "Array" - Arrays and array-like objects
  • "Object" - Plain objects and custom objects
  • "RegExp" - Regular expressions
  • "Date" - Date objects
  • "Error" - Error objects (Error, TypeError, RangeError, etc.)

Wrapped Primitive Types

  • "String" - String objects (new String())
  • "Number" - Number objects (new Number())
  • "Boolean" - Boolean objects (new Boolean())

ES6+ Types

  • "Map" - Map objects
  • "Set" - Set objects
  • "WeakMap" - WeakMap objects
  • "WeakSet" - WeakSet objects
  • "Promise" - Promise objects
  • "DataView" - DataView objects

Iterator Types

  • "Map Iterator" - Map iterator objects
  • "Set Iterator" - Set iterator objects
  • "Array Iterator" - Array iterator objects
  • "String Iterator" - String iterator objects

Typed Array Types

  • "Int8Array", "Uint8Array", "Uint8ClampedArray"
  • "Int16Array", "Uint16Array"
  • "Int32Array", "Uint32Array"
  • "Float32Array", "Float64Array"
  • "ArrayBuffer"

Browser-Specific Types

  • "global" - Global object (window in browsers)
  • "Location" - window.location
  • "Document" - window.document
  • "DOMParser" - DOMParser objects
  • "History" - window.history
  • "Event" - DOM events
  • "HashChangeEvent" - Hash change events
  • "Attr" - DOM attribute objects

Navigator Object Types

  • "Navigator" - window.navigator
  • "Geolocation" - navigator.geolocation
  • "NetworkInformation" - navigator.connection
  • "MediaDevices" - navigator.mediaDevices
  • "MimeTypeArray" - navigator.mimeTypes
  • "NFC" - navigator.nfc
  • "Permissions" - navigator.permissions
  • "PluginArray" - navigator.plugins
  • "Plugin" - Individual plugin objects
  • "Presentation" - navigator.presentation
  • "ServiceWorkerContainer" - navigator.serviceworker
  • "ServicePortCollection" - navigator.services
  • "StorageManager" - navigator.storage
  • "StorageQuota" - navigator.storageQuota
  • "USB" - navigator.usb

HTML Element Types

  • "HTMLElement" - Generic HTML elements
  • "HTMLAreaElement" - <area> elements
  • "HTMLBRElement" - <br> elements
  • "HTMLBaseElement" - <base> elements
  • "HTMLBodyElement" - <body> elements
  • "HTMLButtonElement" - <button> elements
  • "HTMLCanvasElement" - <canvas> elements
  • "HTMLDListElement" - <dl> elements
  • "HTMLDataListElement" - <datalist> elements
  • "HTMLDivElement" - <div> elements
  • "HTMLFieldSetElement" - <fieldset> elements
  • "HTMLFormElement" - <form> elements
  • "HTMLFrameSetElement" - <frameset> elements
  • "HTMLHRElement" - <hr> elements
  • "HTMLHeadElement" - <head> elements
  • "HTMLHeadingElement" - <h1> through <h6> elements
  • "HTMLHtmlElement" - <html> elements
  • "HTMLIFrameElement" - <iframe> elements
  • "HTMLImageElement" - <img> elements
  • "HTMLInputElement" - <input> elements
  • "HTMLLIElement" - <li> elements
  • "HTMLLabelElement" - <label> elements
  • "HTMLLegendElement" - <legend> elements
  • "HTMLLinkElement" - <link> elements
  • "HTMLMapElement" - <map> elements
  • "HTMLMetaElement" - <meta> elements
  • "HTMLMeterElement" - <meter> elements
  • "HTMLModElement" - <del> and <ins> elements
  • "HTMLOListElement" - <ol> elements
  • "HTMLOptGroupElement" - <optgroup> elements
  • "HTMLOptionElement" - <option> elements
  • "HTMLOutputElement" - <output> elements
  • "HTMLParagraphElement" - <p> elements
  • "HTMLParamElement" - <param> elements
  • "HTMLPreElement" - <pre> elements
  • "HTMLProgressElement" - <progress> elements
  • "HTMLQuoteElement" - <blockquote> and <q> elements
  • "HTMLScriptElement" - <script> elements
  • "HTMLSelectElement" - <select> elements
  • "HTMLSpanElement" - <span> elements
  • "HTMLStyleElement" - <style> elements
  • "HTMLTableCaptionElement" - <caption> elements
  • "HTMLTableDataCellElement" - <td> elements
  • "HTMLTableHeaderCellElement" - <th> elements
  • "HTMLTableColElement" - <col> and <colgroup> elements
  • "HTMLTableElement" - <table> elements
  • "HTMLTableRowElement" - <tr> elements
  • "HTMLTableSectionElement" - <thead>, <tbody>, <tfoot> elements
  • "HTMLTextAreaElement" - <textarea> elements
  • "HTMLTitleElement" - <title> elements
  • "HTMLUListElement" - <ul> elements
  • "HTMLUnknownElement" - Unknown/custom HTML elements

Function-Specific Types

  • "Arguments" - Arguments objects
  • "Generator" - Generator objects from generator functions

Node.js-Specific Types

  • "process" - Node.js process object

Custom Types

  • Support for custom types via Symbol.toStringTag

Usage Examples:

import typeDetect from "type-detect";

// Enhanced object detection
const values = [
  [],
  new Array(),
  /regex/gi,
  new RegExp('pattern'),
  new Date(),
  new Map(),
  new Set(),
  new WeakMap(),
  new WeakSet(),
  Symbol('test'),
  Promise.resolve(),
  new Int32Array(10),
  new Float64Array(5),
  new ArrayBuffer(16),
  new DataView(new ArrayBuffer(16))
];

values.forEach(value => {
  console.log(`${value} -> ${typeDetect(value)}`);
});

// Custom types with Symbol.toStringTag
const customObject = {};
customObject[Symbol.toStringTag] = 'CustomType';
console.log(typeDetect(customObject)); // "CustomType"

// Arguments object detection
function testArgs() {
  console.log(typeDetect(arguments)); // "Arguments"
}
testArgs(1, 2, 3);

// Error types
console.log(typeDetect(new Error())); // "Error"
console.log(typeDetect(new TypeError())); // "Error"
console.log(typeDetect(new RangeError())); // "Error"

// Wrapped primitive types
console.log(typeDetect(new Boolean(true))); // "Boolean"

// Generator functions (when supported)
function* generatorFunction() { yield 1; }
const generator = generatorFunction();
console.log(typeDetect(generator)); // "Generator"

// Node.js specific types (when available)
if (typeof process !== 'undefined') {
  console.log(typeDetect(process)); // "process"
}

// Browser DOM elements (when available)
if (typeof window !== 'undefined') {
  console.log(typeDetect(window.location)); // "Location"
  console.log(typeDetect(window.document)); // "Document"
  
  const blockquote = document.createElement('blockquote');
  console.log(typeDetect(blockquote)); // "HTMLQuoteElement"
  
  const td = document.createElement('td');
  console.log(typeDetect(td)); // "HTMLTableDataCellElement"
}

Performance Characteristics:

  • Optimized fast paths for primitive types
  • 20-30x faster than Object.prototype.toString for certain values
  • Minimal memory allocation
  • Consistent performance across different JavaScript engines

Cross-Platform Behavior:

  • Normalizes differences between Node.js, Deno, and browser environments
  • Handles engine-specific quirks and inconsistencies
  • Provides consistent results for modern ECMAScript features
  • Special handling for DOM elements and browser objects when available