0
# Built-in Object Detection
1
2
Type checking functions for JavaScript built-in objects and browser/Node.js specific types. These functions detect standard JavaScript objects and platform-specific types.
3
4
## Capabilities
5
6
### Date Object Detection
7
8
Returns whether the payload is a Date instance.
9
10
```typescript { .api }
11
/**
12
* Returns whether the payload is a Date instance and is a valid date
13
* (not Invalid Date). Uses both type checking and date validity validation.
14
* @param payload - Value to check
15
* @returns Type guard indicating if payload is a valid Date
16
*/
17
function isDate(payload: unknown): payload is Date;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import { isDate } from "is-what";
24
25
isDate(new Date()); // true
26
isDate(new Date("2023-01-01")); // true
27
isDate(new Date("invalid")); // false (Invalid Date)
28
isDate(Date.now()); // false (number timestamp)
29
isDate("2023-01-01"); // false (string)
30
isDate({}); // false
31
32
if (isDate(value)) {
33
// TypeScript knows value is Date
34
console.log(value.getFullYear());
35
console.log(value.toISOString());
36
}
37
38
// Practical usage
39
function formatDate(input: unknown) {
40
if (isDate(input)) {
41
return input.toLocaleDateString();
42
}
43
throw new Error("Input must be a Date object");
44
}
45
```
46
47
### Error Object Detection
48
49
Returns whether the payload is an Error instance.
50
51
```typescript { .api }
52
/**
53
* Returns whether the payload is an Error instance. Uses both type checking
54
* and instanceof validation for comprehensive Error detection.
55
* @param payload - Value to check
56
* @returns Type guard indicating if payload is Error
57
*/
58
function isError(payload: unknown): payload is Error;
59
```
60
61
**Usage Examples:**
62
63
```typescript
64
import { isError } from "is-what";
65
66
isError(new Error("test")); // true
67
isError(new TypeError("test")); // true
68
isError(new RangeError("test")); // true
69
isError({ message: "error" }); // false (error-like object)
70
isError("Error: something"); // false (string)
71
72
// Error handling
73
function handleResult(result: unknown) {
74
if (isError(result)) {
75
console.error("Operation failed:", result.message);
76
console.error("Stack:", result.stack);
77
return null;
78
}
79
80
return result;
81
}
82
83
// Type-safe error checking
84
function processWithErrorHandling(operation: () => unknown) {
85
try {
86
return operation();
87
} catch (error) {
88
if (isError(error)) {
89
// TypeScript knows error is Error
90
return { success: false, error: error.message };
91
}
92
93
// Handle non-Error throws
94
return { success: false, error: "Unknown error occurred" };
95
}
96
}
97
```
98
99
### RegExp Detection
100
101
Returns whether the payload is a RegExp instance.
102
103
```typescript { .api }
104
/**
105
* Returns whether the payload is a RegExp instance
106
* @param payload - Value to check
107
* @returns Type guard indicating if payload is RegExp
108
*/
109
function isRegExp(payload: unknown): payload is RegExp;
110
```
111
112
**Usage Examples:**
113
114
```typescript
115
import { isRegExp } from "is-what";
116
117
isRegExp(/abc/); // true
118
isRegExp(new RegExp("abc")); // true
119
isRegExp("/abc/"); // false (string)
120
isRegExp({}); // false
121
122
if (isRegExp(pattern)) {
123
// TypeScript knows pattern is RegExp
124
console.log(pattern.test("abc"));
125
console.log(pattern.source);
126
console.log(pattern.flags);
127
}
128
129
// Pattern validation
130
function validatePattern(input: unknown) {
131
if (isRegExp(input)) {
132
return { valid: true, pattern: input };
133
}
134
135
return { valid: false, error: "Must be a regular expression" };
136
}
137
```
138
139
### Map Detection
140
141
Returns whether the payload is a Map instance.
142
143
```typescript { .api }
144
/**
145
* Returns whether the payload is a Map instance
146
* @param payload - Value to check
147
* @returns Type guard indicating if payload is Map
148
*/
149
function isMap(payload: unknown): payload is Map<unknown, unknown>;
150
```
151
152
**Usage Examples:**
153
154
```typescript
155
import { isMap } from "is-what";
156
157
isMap(new Map()); // true
158
isMap(new Map([["a", 1], ["b", 2]])); // true
159
isMap({}); // false (plain object)
160
isMap(new Set()); // false (Set, not Map)
161
162
if (isMap(collection)) {
163
// TypeScript knows collection is Map
164
console.log(collection.size);
165
collection.set("key", "value");
166
console.log(collection.get("key"));
167
}
168
169
// Map processing
170
function processMapData(input: unknown) {
171
if (isMap(input)) {
172
const entries = Array.from(input.entries());
173
return entries.map(([key, value]) => ({ key, value }));
174
}
175
176
return null;
177
}
178
```
179
180
### Set Detection
181
182
Returns whether the payload is a Set instance.
183
184
```typescript { .api }
185
/**
186
* Returns whether the payload is a Set instance
187
* @param payload - Value to check
188
* @returns Type guard indicating if payload is Set
189
*/
190
function isSet(payload: unknown): payload is Set<unknown>;
191
```
192
193
**Usage Examples:**
194
195
```typescript
196
import { isSet } from "is-what";
197
198
isSet(new Set()); // true
199
isSet(new Set([1, 2, 3])); // true
200
isSet([]); // false (array)
201
isSet(new Map()); // false (Map, not Set)
202
203
if (isSet(collection)) {
204
// TypeScript knows collection is Set
205
console.log(collection.size);
206
collection.add("new item");
207
console.log(collection.has("item"));
208
}
209
210
// Set operations
211
function convertToArray(input: unknown) {
212
if (isSet(input)) {
213
return Array.from(input);
214
}
215
216
throw new Error("Input must be a Set");
217
}
218
```
219
220
### WeakMap Detection
221
222
Returns whether the payload is a WeakMap instance.
223
224
```typescript { .api }
225
/**
226
* Returns whether the payload is a WeakMap instance
227
* @param payload - Value to check
228
* @returns Type guard indicating if payload is WeakMap
229
*/
230
function isWeakMap(payload: unknown): payload is WeakMap<object, unknown>;
231
```
232
233
**Usage Examples:**
234
235
```typescript
236
import { isWeakMap } from "is-what";
237
238
isWeakMap(new WeakMap()); // true
239
isWeakMap(new Map()); // false (Map, not WeakMap)
240
isWeakMap({}); // false
241
242
const obj = {};
243
if (isWeakMap(weakRef)) {
244
// TypeScript knows weakRef is WeakMap
245
weakRef.set(obj, "associated data");
246
console.log(weakRef.get(obj));
247
}
248
```
249
250
### WeakSet Detection
251
252
Returns whether the payload is a WeakSet instance.
253
254
```typescript { .api }
255
/**
256
* Returns whether the payload is a WeakSet instance
257
* @param payload - Value to check
258
* @returns Type guard indicating if payload is WeakSet
259
*/
260
function isWeakSet(payload: unknown): payload is WeakSet<object>;
261
```
262
263
### Promise Detection
264
265
Returns whether the payload is a Promise instance.
266
267
```typescript { .api }
268
/**
269
* Returns whether the payload is a Promise instance
270
* @param payload - Value to check
271
* @returns Type guard indicating if payload is Promise
272
*/
273
function isPromise(payload: unknown): payload is Promise<unknown>;
274
```
275
276
**Usage Examples:**
277
278
```typescript
279
import { isPromise } from "is-what";
280
281
isPromise(Promise.resolve(1)); // true
282
isPromise(new Promise(resolve => resolve(1))); // true
283
isPromise(async function() {}()); // true (async functions return promises)
284
isPromise({ then: () => {} }); // false (thenable, but not Promise)
285
isPromise("promise"); // false
286
287
// Async handling
288
async function handleAsyncResult(result: unknown) {
289
if (isPromise(result)) {
290
// TypeScript knows result is Promise
291
try {
292
const resolved = await result;
293
return { success: true, data: resolved };
294
} catch (error) {
295
return { success: false, error };
296
}
297
}
298
299
// Synchronous result
300
return { success: true, data: result };
301
}
302
303
// Promise detection in utilities
304
function maybeAwait(value: unknown) {
305
if (isPromise(value)) {
306
return value; // Return the promise to be awaited
307
}
308
309
return Promise.resolve(value); // Wrap non-promise in resolved promise
310
}
311
```
312
313
### Browser-Specific Types
314
315
#### Blob Detection
316
317
Returns whether the payload is a Blob instance (browser environments).
318
319
```typescript { .api }
320
/**
321
* Returns whether the payload is a Blob instance
322
* @param payload - Value to check
323
* @returns Type guard indicating if payload is Blob
324
*/
325
function isBlob(payload: unknown): payload is Blob;
326
```
327
328
#### File Detection
329
330
Returns whether the payload is a File instance (browser environments).
331
332
```typescript { .api }
333
/**
334
* Returns whether the payload is a File instance
335
* @param payload - Value to check
336
* @returns Type guard indicating if payload is File
337
*/
338
function isFile(payload: unknown): payload is File;
339
```
340
341
**Usage Examples:**
342
343
```typescript
344
import { isBlob, isFile } from "is-what";
345
346
// Browser environment
347
if (typeof Blob !== 'undefined') {
348
const blob = new Blob(['content'], { type: 'text/plain' });
349
isBlob(blob); // true
350
351
// File extends Blob
352
const file = new File(['content'], 'test.txt', { type: 'text/plain' });
353
isFile(file); // true
354
isBlob(file); // true (File extends Blob)
355
}
356
357
// File upload handling
358
function handleFileUpload(input: unknown) {
359
if (isFile(input)) {
360
// TypeScript knows input is File
361
return {
362
name: input.name,
363
size: input.size,
364
type: input.type,
365
lastModified: input.lastModified
366
};
367
}
368
369
if (isBlob(input)) {
370
// TypeScript knows input is Blob
371
return {
372
size: input.size,
373
type: input.type
374
};
375
}
376
377
throw new Error("Input must be a File or Blob");
378
}
379
```
380
381
## Combined Built-in Type Patterns
382
383
```typescript
384
import {
385
isDate,
386
isError,
387
isRegExp,
388
isMap,
389
isSet,
390
isPromise
391
} from "is-what";
392
393
function analyzeBuiltinType(value: unknown) {
394
if (isDate(value)) {
395
return `Date: ${value.toISOString()}`;
396
}
397
398
if (isError(value)) {
399
return `Error: ${value.message}`;
400
}
401
402
if (isRegExp(value)) {
403
return `RegExp: ${value.source} (flags: ${value.flags})`;
404
}
405
406
if (isMap(value)) {
407
return `Map with ${value.size} entries`;
408
}
409
410
if (isSet(value)) {
411
return `Set with ${value.size} items`;
412
}
413
414
if (isPromise(value)) {
415
return "Promise (pending/resolved/rejected)";
416
}
417
418
return "Not a recognized built-in type";
419
}
420
421
// Collection utilities
422
function processCollection(collection: unknown) {
423
if (isMap(collection)) {
424
return {
425
type: "Map",
426
size: collection.size,
427
entries: Array.from(collection.entries())
428
};
429
}
430
431
if (isSet(collection)) {
432
return {
433
type: "Set",
434
size: collection.size,
435
values: Array.from(collection.values())
436
};
437
}
438
439
return null;
440
}
441
442
// Example usage
443
analyzeBuiltinType(new Date()); // "Date: 2023-01-01T00:00:00.000Z"
444
analyzeBuiltinType(/abc/g); // "RegExp: abc (flags: g)"
445
analyzeBuiltinType(new Map([["a", 1]])); // "Map with 1 entries"
446
analyzeBuiltinType(new Error("test")); // "Error: test"
447
```