0
# Type Detect
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: type-detect
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install type-detect`
10
11
## Core Imports
12
13
```typescript
14
import typeDetect from "type-detect";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const typeDetect = require("type-detect");
21
```
22
23
For Deno:
24
25
```typescript
26
import typeDetect from "https://deno.land/x/type_detect@v4.1.0/index.ts";
27
```
28
29
For browsers (UMD):
30
31
```html
32
<script src="./node_modules/type-detect/type-detect.js"></script>
33
<script>
34
var typeDetect = typeDetect; // Available globally
35
</script>
36
```
37
38
## Basic Usage
39
40
```typescript
41
import typeDetect from "type-detect";
42
43
// Basic types
44
console.log(typeDetect("hello")); // "string"
45
console.log(typeDetect(42)); // "number"
46
console.log(typeDetect(true)); // "boolean"
47
console.log(typeDetect(null)); // "null"
48
console.log(typeDetect(undefined)); // "undefined"
49
50
// Objects and arrays
51
console.log(typeDetect([])); // "Array"
52
console.log(typeDetect({})); // "Object"
53
console.log(typeDetect(/regex/)); // "RegExp"
54
console.log(typeDetect(new Date())); // "Date"
55
56
// ES6+ types
57
console.log(typeDetect(new Map())); // "Map"
58
console.log(typeDetect(new Set())); // "Set"
59
console.log(typeDetect(Symbol())); // "symbol"
60
console.log(typeDetect(Promise.resolve())); // "Promise"
61
62
// Typed arrays
63
console.log(typeDetect(new Int32Array())); // "Int32Array"
64
console.log(typeDetect(new Float64Array())); // "Float64Array"
65
66
// Browser DOM elements (when available)
67
if (typeof document !== 'undefined') {
68
console.log(typeDetect(document)); // "Document"
69
console.log(typeDetect(document.createElement('div'))); // "HTMLDivElement"
70
}
71
```
72
73
## Architecture
74
75
Type Detect uses a carefully optimized algorithm that:
76
77
- **Performance First**: Specialized checks that are 20-30x faster than Object.prototype.toString for certain values
78
- **Cross-Platform**: Normalizes behavior across Node.js, Deno, and different browser engines
79
- **Modern Types**: Full support for ES6+ types, iterators, and typed arrays
80
- **Browser DOM**: Special handling for DOM elements and browser-specific objects
81
- **Zero Dependencies**: No runtime dependencies for minimal footprint
82
83
## Capabilities
84
85
### Enhanced Type Detection
86
87
The core type detection functionality that serves as a drop-in replacement for JavaScript's `typeof` operator with enhanced specificity and cross-platform consistency.
88
89
```typescript { .api }
90
function typeDetect(obj: unknown): string;
91
```
92
93
**Parameters:**
94
- `obj` (`unknown`): The value to analyze for type detection
95
96
**Returns:**
97
- `string`: A string representing the detected type
98
99
**Supported Return Types:**
100
101
#### Primitive Types
102
- `"string"` - String literals
103
- `"number"` - Number literals (including Infinity, NaN)
104
- `"boolean"` - Boolean literals
105
- `"undefined"` - Undefined values
106
- `"function"` - Function objects
107
- `"symbol"` - Symbol values
108
109
#### Object Types
110
- `"null"` - Null values
111
- `"Array"` - Arrays and array-like objects
112
- `"Object"` - Plain objects and custom objects
113
- `"RegExp"` - Regular expressions
114
- `"Date"` - Date objects
115
- `"Error"` - Error objects (Error, TypeError, RangeError, etc.)
116
117
#### Wrapped Primitive Types
118
- `"String"` - String objects (new String())
119
- `"Number"` - Number objects (new Number())
120
- `"Boolean"` - Boolean objects (new Boolean())
121
122
#### ES6+ Types
123
- `"Map"` - Map objects
124
- `"Set"` - Set objects
125
- `"WeakMap"` - WeakMap objects
126
- `"WeakSet"` - WeakSet objects
127
- `"Promise"` - Promise objects
128
- `"DataView"` - DataView objects
129
130
#### Iterator Types
131
- `"Map Iterator"` - Map iterator objects
132
- `"Set Iterator"` - Set iterator objects
133
- `"Array Iterator"` - Array iterator objects
134
- `"String Iterator"` - String iterator objects
135
136
#### Typed Array Types
137
- `"Int8Array"`, `"Uint8Array"`, `"Uint8ClampedArray"`
138
- `"Int16Array"`, `"Uint16Array"`
139
- `"Int32Array"`, `"Uint32Array"`
140
- `"Float32Array"`, `"Float64Array"`
141
- `"ArrayBuffer"`
142
143
#### Browser-Specific Types
144
- `"global"` - Global object (window in browsers)
145
- `"Location"` - window.location
146
- `"Document"` - window.document
147
- `"DOMParser"` - DOMParser objects
148
- `"History"` - window.history
149
- `"Event"` - DOM events
150
- `"HashChangeEvent"` - Hash change events
151
- `"Attr"` - DOM attribute objects
152
153
#### Navigator Object Types
154
- `"Navigator"` - window.navigator
155
- `"Geolocation"` - navigator.geolocation
156
- `"NetworkInformation"` - navigator.connection
157
- `"MediaDevices"` - navigator.mediaDevices
158
- `"MimeTypeArray"` - navigator.mimeTypes
159
- `"NFC"` - navigator.nfc
160
- `"Permissions"` - navigator.permissions
161
- `"PluginArray"` - navigator.plugins
162
- `"Plugin"` - Individual plugin objects
163
- `"Presentation"` - navigator.presentation
164
- `"ServiceWorkerContainer"` - navigator.serviceworker
165
- `"ServicePortCollection"` - navigator.services
166
- `"StorageManager"` - navigator.storage
167
- `"StorageQuota"` - navigator.storageQuota
168
- `"USB"` - navigator.usb
169
170
#### HTML Element Types
171
- `"HTMLElement"` - Generic HTML elements
172
- `"HTMLAreaElement"` - `<area>` elements
173
- `"HTMLBRElement"` - `<br>` elements
174
- `"HTMLBaseElement"` - `<base>` elements
175
- `"HTMLBodyElement"` - `<body>` elements
176
- `"HTMLButtonElement"` - `<button>` elements
177
- `"HTMLCanvasElement"` - `<canvas>` elements
178
- `"HTMLDListElement"` - `<dl>` elements
179
- `"HTMLDataListElement"` - `<datalist>` elements
180
- `"HTMLDivElement"` - `<div>` elements
181
- `"HTMLFieldSetElement"` - `<fieldset>` elements
182
- `"HTMLFormElement"` - `<form>` elements
183
- `"HTMLFrameSetElement"` - `<frameset>` elements
184
- `"HTMLHRElement"` - `<hr>` elements
185
- `"HTMLHeadElement"` - `<head>` elements
186
- `"HTMLHeadingElement"` - `<h1>` through `<h6>` elements
187
- `"HTMLHtmlElement"` - `<html>` elements
188
- `"HTMLIFrameElement"` - `<iframe>` elements
189
- `"HTMLImageElement"` - `<img>` elements
190
- `"HTMLInputElement"` - `<input>` elements
191
- `"HTMLLIElement"` - `<li>` elements
192
- `"HTMLLabelElement"` - `<label>` elements
193
- `"HTMLLegendElement"` - `<legend>` elements
194
- `"HTMLLinkElement"` - `<link>` elements
195
- `"HTMLMapElement"` - `<map>` elements
196
- `"HTMLMetaElement"` - `<meta>` elements
197
- `"HTMLMeterElement"` - `<meter>` elements
198
- `"HTMLModElement"` - `<del>` and `<ins>` elements
199
- `"HTMLOListElement"` - `<ol>` elements
200
- `"HTMLOptGroupElement"` - `<optgroup>` elements
201
- `"HTMLOptionElement"` - `<option>` elements
202
- `"HTMLOutputElement"` - `<output>` elements
203
- `"HTMLParagraphElement"` - `<p>` elements
204
- `"HTMLParamElement"` - `<param>` elements
205
- `"HTMLPreElement"` - `<pre>` elements
206
- `"HTMLProgressElement"` - `<progress>` elements
207
- `"HTMLQuoteElement"` - `<blockquote>` and `<q>` elements
208
- `"HTMLScriptElement"` - `<script>` elements
209
- `"HTMLSelectElement"` - `<select>` elements
210
- `"HTMLSpanElement"` - `<span>` elements
211
- `"HTMLStyleElement"` - `<style>` elements
212
- `"HTMLTableCaptionElement"` - `<caption>` elements
213
- `"HTMLTableDataCellElement"` - `<td>` elements
214
- `"HTMLTableHeaderCellElement"` - `<th>` elements
215
- `"HTMLTableColElement"` - `<col>` and `<colgroup>` elements
216
- `"HTMLTableElement"` - `<table>` elements
217
- `"HTMLTableRowElement"` - `<tr>` elements
218
- `"HTMLTableSectionElement"` - `<thead>`, `<tbody>`, `<tfoot>` elements
219
- `"HTMLTextAreaElement"` - `<textarea>` elements
220
- `"HTMLTitleElement"` - `<title>` elements
221
- `"HTMLUListElement"` - `<ul>` elements
222
- `"HTMLUnknownElement"` - Unknown/custom HTML elements
223
224
#### Function-Specific Types
225
- `"Arguments"` - Arguments objects
226
- `"Generator"` - Generator objects from generator functions
227
228
#### Node.js-Specific Types
229
- `"process"` - Node.js process object
230
231
#### Custom Types
232
- Support for custom types via `Symbol.toStringTag`
233
234
**Usage Examples:**
235
236
```typescript
237
import typeDetect from "type-detect";
238
239
// Enhanced object detection
240
const values = [
241
[],
242
new Array(),
243
/regex/gi,
244
new RegExp('pattern'),
245
new Date(),
246
new Map(),
247
new Set(),
248
new WeakMap(),
249
new WeakSet(),
250
Symbol('test'),
251
Promise.resolve(),
252
new Int32Array(10),
253
new Float64Array(5),
254
new ArrayBuffer(16),
255
new DataView(new ArrayBuffer(16))
256
];
257
258
values.forEach(value => {
259
console.log(`${value} -> ${typeDetect(value)}`);
260
});
261
262
// Custom types with Symbol.toStringTag
263
const customObject = {};
264
customObject[Symbol.toStringTag] = 'CustomType';
265
console.log(typeDetect(customObject)); // "CustomType"
266
267
// Arguments object detection
268
function testArgs() {
269
console.log(typeDetect(arguments)); // "Arguments"
270
}
271
testArgs(1, 2, 3);
272
273
// Error types
274
console.log(typeDetect(new Error())); // "Error"
275
console.log(typeDetect(new TypeError())); // "Error"
276
console.log(typeDetect(new RangeError())); // "Error"
277
278
// Wrapped primitive types
279
console.log(typeDetect(new Boolean(true))); // "Boolean"
280
281
// Generator functions (when supported)
282
function* generatorFunction() { yield 1; }
283
const generator = generatorFunction();
284
console.log(typeDetect(generator)); // "Generator"
285
286
// Node.js specific types (when available)
287
if (typeof process !== 'undefined') {
288
console.log(typeDetect(process)); // "process"
289
}
290
291
// Browser DOM elements (when available)
292
if (typeof window !== 'undefined') {
293
console.log(typeDetect(window.location)); // "Location"
294
console.log(typeDetect(window.document)); // "Document"
295
296
const blockquote = document.createElement('blockquote');
297
console.log(typeDetect(blockquote)); // "HTMLQuoteElement"
298
299
const td = document.createElement('td');
300
console.log(typeDetect(td)); // "HTMLTableDataCellElement"
301
}
302
```
303
304
**Performance Characteristics:**
305
- Optimized fast paths for primitive types
306
- 20-30x faster than Object.prototype.toString for certain values
307
- Minimal memory allocation
308
- Consistent performance across different JavaScript engines
309
310
**Cross-Platform Behavior:**
311
- Normalizes differences between Node.js, Deno, and browser environments
312
- Handles engine-specific quirks and inconsistencies
313
- Provides consistent results for modern ECMAScript features
314
- Special handling for DOM elements and browser objects when available