0
# Type Guards & Validation
1
2
**DEPRECATED**: Import all functions from `@sentry/core` instead of `@sentry/utils`.
3
4
Comprehensive type checking utilities for safe runtime type detection and validation across different JavaScript environments.
5
6
## Capabilities
7
8
### Basic Type Guards
9
10
Core type checking functions for primitive and common JavaScript types.
11
12
```typescript { .api }
13
/**
14
* Type guard for plain objects (not arrays, functions, or null)
15
* @param wat - Value to check
16
* @returns True if value is a plain object
17
*/
18
function isPlainObject(wat: unknown): wat is Record<string, any>;
19
20
/**
21
* Type guard for primitive values (string, number, boolean, null, undefined, symbol, bigint)
22
* @param wat - Value to check
23
* @returns True if value is a primitive
24
*/
25
function isPrimitive(wat: unknown): wat is Primitive;
26
27
/**
28
* Type guard for string values
29
* @param wat - Value to check
30
* @returns True if value is a string
31
*/
32
function isString(wat: unknown): wat is string;
33
34
/**
35
* Type guard for RegExp objects
36
* @param wat - Value to check
37
* @returns True if value is a RegExp
38
*/
39
function isRegExp(wat: unknown): wat is RegExp;
40
41
/**
42
* Type guard for parameterized strings (template literals with placeholders)
43
* @param wat - Value to check
44
* @returns True if value is a parameterized string
45
*/
46
function isParameterizedString(wat: unknown): wat is string;
47
```
48
49
**Usage Examples:**
50
51
```typescript
52
import { isPlainObject, isPrimitive, isString } from "@sentry/core";
53
54
function processData(data: unknown) {
55
if (isString(data)) {
56
return data.toUpperCase(); // Safe to call string methods
57
}
58
59
if (isPlainObject(data)) {
60
return Object.keys(data).length; // Safe to treat as object
61
}
62
63
if (isPrimitive(data)) {
64
return String(data); // Safe to convert primitive
65
}
66
67
return null;
68
}
69
```
70
71
### Promise & Async Type Guards
72
73
Type guards for promise-like objects and async operations.
74
75
```typescript { .api }
76
/**
77
* Type guard for thenable objects (objects with a 'then' method)
78
* @param wat - Value to check
79
* @returns True if value is thenable
80
*/
81
function isThenable(wat: any): wat is PromiseLike<any>;
82
```
83
84
**Usage Example:**
85
86
```typescript
87
import { isThenable } from "@sentry/core";
88
89
function handleResult(result: unknown) {
90
if (isThenable(result)) {
91
return result.then(value => console.log('Resolved:', value));
92
} else {
93
console.log('Synchronous result:', result);
94
return result;
95
}
96
}
97
```
98
99
### DOM & Browser Type Guards
100
101
Type guards for DOM elements and browser-specific objects.
102
103
```typescript { .api }
104
/**
105
* Type guard for DOM Element objects
106
* @param wat - Value to check
107
* @returns True if value is a DOM Element
108
*/
109
function isElement(wat: unknown): wat is Element;
110
111
/**
112
* Type guard for Event objects
113
* @param wat - Value to check
114
* @returns True if value is an Event
115
*/
116
function isEvent(wat: unknown): wat is Event;
117
118
/**
119
* Type guard for synthetic events (React-style events)
120
* @param wat - Value to check
121
* @returns True if value appears to be a synthetic event
122
*/
123
function isSyntheticEvent(wat: unknown): wat is { [key: string]: any };
124
125
/**
126
* Type guard for Vue.js view model objects
127
* @param wat - Value to check
128
* @returns True if value is a Vue view model
129
*/
130
function isVueViewModel(wat: unknown): wat is { [key: string]: any };
131
```
132
133
**Usage Examples:**
134
135
```typescript
136
import { isElement, isEvent, isSyntheticEvent } from "@sentry/core";
137
138
function handleDOMValue(value: unknown) {
139
if (isElement(value)) {
140
return value.tagName; // Safe to access Element properties
141
}
142
143
if (isEvent(value)) {
144
return value.type; // Safe to access Event properties
145
}
146
147
if (isSyntheticEvent(value)) {
148
// Handle React synthetic events
149
return value.nativeEvent || value;
150
}
151
152
return null;
153
}
154
155
// Event handler that works with both native and synthetic events
156
function handleClick(event: unknown) {
157
if (isEvent(event)) {
158
event.preventDefault();
159
} else if (isSyntheticEvent(event)) {
160
event.preventDefault?.();
161
}
162
}
163
```
164
165
### Safe instanceof Checking
166
167
Safe instanceof checking that handles edge cases and cross-frame scenarios.
168
169
```typescript { .api }
170
/**
171
* Safe instanceof check that handles cross-frame scenarios
172
* @param wat - Object to check
173
* @param base - Constructor function or object to check against
174
* @returns True if wat is an instance of base
175
*/
176
function isInstanceOf(wat: any, base: any): boolean;
177
```
178
179
**Usage Example:**
180
181
```typescript
182
import { isInstanceOf } from "@sentry/core";
183
184
function checkInstance(obj: unknown) {
185
// Safe even across different window/frame contexts
186
if (isInstanceOf(obj, Error)) {
187
return obj.message;
188
}
189
190
if (isInstanceOf(obj, Date)) {
191
return obj.toISOString();
192
}
193
194
return null;
195
}
196
```
197
198
### Pattern Matching
199
200
Utilities for matching values against patterns or regular expressions.
201
202
```typescript { .api }
203
/**
204
* Checks if a value matches any of the provided patterns
205
* @param wat - Value to check (will be converted to string)
206
* @param patterns - Array of strings or RegExp patterns to match against
207
* @returns True if value matches any pattern
208
*/
209
function isMatchingPattern(wat: string, patterns: Array<string | RegExp>): boolean;
210
```
211
212
**Usage Example:**
213
214
```typescript
215
import { isMatchingPattern } from "@sentry/core";
216
217
const ignoredErrors = [
218
'Script error',
219
/network.*error/i,
220
'ResizeObserver loop limit exceeded'
221
];
222
223
function shouldIgnoreError(errorMessage: string): boolean {
224
return isMatchingPattern(errorMessage, ignoredErrors);
225
}
226
227
// Usage in error handler
228
if (shouldIgnoreError(error.message)) {
229
return; // Skip processing this error
230
}
231
```
232
233
## Type Guard Patterns
234
235
### Combining Type Guards
236
237
Type guards can be combined for more complex type checking:
238
239
```typescript
240
import { isPlainObject, isString, isThenable } from "@sentry/core";
241
242
interface User {
243
id: string;
244
name: string;
245
email?: string;
246
}
247
248
function isUser(obj: unknown): obj is User {
249
return (
250
isPlainObject(obj) &&
251
isString(obj.id) &&
252
isString(obj.name) &&
253
(obj.email === undefined || isString(obj.email))
254
);
255
}
256
257
function processUserData(data: unknown) {
258
if (isUser(data)) {
259
// TypeScript knows data is User here
260
console.log(`Processing user: ${data.name}`);
261
return data;
262
}
263
264
throw new Error('Invalid user data');
265
}
266
```
267
268
### Runtime Validation
269
270
Type guards are useful for runtime validation of API responses and user input:
271
272
```typescript
273
import { isPlainObject, isString, isThenable } from "@sentry/core";
274
275
async function fetchUserData(id: string) {
276
const response = await fetch(`/api/users/${id}`);
277
const data = await response.json();
278
279
// Validate response structure
280
if (!isPlainObject(data)) {
281
throw new Error('Invalid API response: not an object');
282
}
283
284
if (!isString(data.name)) {
285
throw new Error('Invalid API response: missing name');
286
}
287
288
return data;
289
}
290
```
291
292
### Framework Integration
293
294
Type guards help with framework-specific type checking:
295
296
```typescript
297
import { isSyntheticEvent, isVueViewModel } from "@sentry/core";
298
299
function handleFrameworkEvent(event: unknown, framework: 'react' | 'vue') {
300
if (framework === 'react' && isSyntheticEvent(event)) {
301
// Handle React synthetic event
302
const nativeEvent = event.nativeEvent;
303
return nativeEvent;
304
}
305
306
if (framework === 'vue' && isVueViewModel(event)) {
307
// Handle Vue component event
308
return event.$el;
309
}
310
311
return event;
312
}
313
```
314
315
## Types
316
317
```typescript { .api }
318
type Primitive =
319
| null
320
| undefined
321
| string
322
| number
323
| boolean
324
| symbol
325
| bigint;
326
327
interface PlainObject {
328
[key: string]: any;
329
}
330
```
331
332
**Migration Note**: All type guard functions have been moved from `@sentry/utils` to `@sentry/core`. Update your imports accordingly.