0
# Utilities
1
2
Core utility functions including filters, type checking, promise helpers, and general-purpose functions that support VueUse shared functionality.
3
4
## Capabilities
5
6
### Filter Utilities
7
8
Event filtering functions for debouncing, throttling, and pausing function execution.
9
10
```typescript { .api }
11
/**
12
* Create debounce filter for function execution
13
* @param ms - Debounce delay in milliseconds
14
* @param options - Debounce options
15
* @returns Event filter function
16
*/
17
function debounceFilter(
18
ms: MaybeRefOrGetter<number>,
19
options?: DebounceFilterOptions
20
): EventFilter;
21
22
/**
23
* Create throttle filter for function execution
24
* @param ms - Throttle delay in milliseconds
25
* @param trailing - Execute on trailing edge
26
* @param leading - Execute on leading edge
27
* @param rejectOnCancel - Reject promise when cancelled
28
* @returns Event filter function
29
*/
30
function throttleFilter(
31
ms: MaybeRefOrGetter<number>,
32
trailing?: boolean,
33
leading?: boolean,
34
rejectOnCancel?: boolean
35
): EventFilter;
36
37
/**
38
* Create pausable filter that can be paused and resumed
39
* @param extendFilter - Optional additional filter to extend
40
* @returns Pausable event filter
41
*/
42
function pausableFilter(extendFilter?: EventFilter): Pausable & { eventFilter: EventFilter };
43
44
/**
45
* Bypass filter - passes through all events
46
*/
47
const bypassFilter: EventFilter;
48
49
/**
50
* Create filter wrapper for functions
51
* @param filter - Event filter to apply
52
* @param fn - Function to wrap
53
* @returns Wrapped function with filter applied
54
*/
55
function createFilterWrapper<T extends AnyFn>(filter: EventFilter, fn: T): T;
56
57
interface DebounceFilterOptions {
58
maxWait?: MaybeRefOrGetter<number>;
59
rejectOnCancel?: boolean;
60
}
61
62
type EventFilter<Args extends any[] = any[], This = any, Invoke extends AnyFn = AnyFn> = (
63
invoke: Invoke,
64
options: FunctionWrapperOptions<Args, This>
65
) => ReturnType<Invoke> | Promisify<ReturnType<Invoke>>;
66
```
67
68
**Usage Example:**
69
70
```typescript
71
import { debounceFilter, throttleFilter, useDebounceFn } from "@vueuse/shared";
72
73
// Create custom debounced function
74
const debouncedFn = useDebounceFn(
75
() => console.log('Executed!'),
76
300
77
);
78
79
// Using filters directly
80
const filter = debounceFilter(500, { maxWait: 1000 });
81
const throttled = throttleFilter(200, true, true);
82
```
83
84
### Type Checking Utilities
85
86
Environment detection and type checking functions.
87
88
```typescript { .api }
89
/**
90
* Check if running in client environment (browser)
91
*/
92
const isClient: boolean;
93
94
/**
95
* Check if running in Web Worker environment
96
*/
97
const isWorker: boolean;
98
99
/**
100
* Check if value is defined (not undefined)
101
* @param val - Value to check
102
* @returns Type predicate for defined value
103
*/
104
function isDef<T = any>(val?: T): val is T;
105
106
/**
107
* Check if value is not null or undefined
108
* @param val - Value to check
109
* @returns Type predicate for non-nullish value
110
*/
111
function notNullish<T = any>(val?: T | null | undefined): val is T;
112
113
/**
114
* Assert condition with console warning
115
* @param condition - Condition to assert
116
* @param infos - Additional info to log
117
*/
118
function assert(condition: boolean, ...infos: any[]): void;
119
120
/**
121
* Check if value is plain object
122
* @param val - Value to check
123
* @returns Type predicate for object
124
*/
125
function isObject(val: any): val is object;
126
127
/**
128
* Check if running on iOS device
129
*/
130
const isIOS: boolean;
131
132
/**
133
* Check if object has own property
134
* @param val - Object to check
135
* @param key - Property key
136
* @returns Type predicate for property existence
137
*/
138
function hasOwn<T extends object, K extends keyof T>(val: T, key: K): key is K;
139
```
140
141
**Usage Example:**
142
143
```typescript
144
import { isClient, isDef, notNullish, isObject } from "@vueuse/shared";
145
146
// Environment checks
147
if (isClient) {
148
console.log('Running in browser');
149
}
150
151
// Type guards
152
const value: unknown = getData();
153
if (isDef(value) && notNullish(value)) {
154
// value is defined and not null/undefined
155
console.log(value);
156
}
157
158
if (isObject(value)) {
159
// value is a plain object
160
Object.keys(value).forEach(key => {
161
if (hasOwn(value, key)) {
162
console.log(value[key]);
163
}
164
});
165
}
166
```
167
168
### General Purpose Utilities
169
170
Utility functions for common operations.
171
172
```typescript { .api }
173
/**
174
* Current timestamp in milliseconds
175
* @returns Current Date.now() value
176
*/
177
function now(): number;
178
179
/**
180
* Current timestamp (alias for now)
181
* @returns Current timestamp
182
*/
183
function timestamp(): number;
184
185
/**
186
* Clamp number between min and max values
187
* @param n - Number to clamp
188
* @param min - Minimum value
189
* @param max - Maximum value
190
* @returns Clamped value
191
*/
192
function clamp(n: number, min: number, max: number): number;
193
194
/**
195
* No-operation function
196
*/
197
function noop(): void;
198
199
/**
200
* Generate random integer between min and max (inclusive)
201
* @param min - Minimum value
202
* @param max - Maximum value
203
* @returns Random integer
204
*/
205
function rand(min: number, max: number): number;
206
207
/**
208
* Identity function - returns input unchanged
209
* @param arg - Input value
210
* @returns Same value
211
*/
212
function identity<T>(arg: T): T;
213
214
/**
215
* Convert value to array
216
* @param array - Value or array
217
* @returns Array containing the value(s)
218
*/
219
function toArray<T>(array: T | T[]): T[];
220
```
221
222
**Usage Example:**
223
224
```typescript
225
import { now, clamp, rand, identity, toArray } from "@vueuse/shared";
226
227
// Timestamps
228
const currentTime = now();
229
const timestamp = timestamp();
230
231
// Math utilities
232
const clamped = clamp(150, 0, 100); // 100
233
const randomNum = rand(1, 10); // Random number 1-10
234
235
// Utilities
236
const unchanged = identity('hello'); // 'hello'
237
const array = toArray('single'); // ['single']
238
const stillArray = toArray(['a', 'b']); // ['a', 'b']
239
```
240
241
### Promise Utilities
242
243
Utilities for working with promises and async operations.
244
245
```typescript { .api }
246
/**
247
* Create promise that resolves after specified time
248
* @param ms - Milliseconds to wait
249
* @param throwOnTimeout - Whether to reject instead of resolve
250
* @param reason - Rejection reason when throwOnTimeout is true
251
* @returns Promise that resolves/rejects after delay
252
*/
253
function promiseTimeout(
254
ms: number,
255
throwOnTimeout?: boolean,
256
reason?: string
257
): Promise<void>;
258
259
/**
260
* Create singleton promise function
261
* @param fn - Async function to wrap
262
* @returns Singleton promise function with reset capability
263
*/
264
function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
265
266
interface SingletonPromiseReturn<T> {
267
(): Promise<T>;
268
reset: () => Promise<void>;
269
}
270
271
/**
272
* Invoke function with arguments
273
* @param fn - Function to invoke
274
* @param args - Arguments to pass
275
* @returns Function result
276
*/
277
function invoke<T>(fn: () => T): T;
278
function invoke<T extends any[], R>(fn: (...args: T) => R, ...args: T): R;
279
```
280
281
**Usage Example:**
282
283
```typescript
284
import { promiseTimeout, createSingletonPromise } from "@vueuse/shared";
285
286
// Promise timeout
287
await promiseTimeout(1000); // Wait 1 second
288
await promiseTimeout(5000, true, 'Request timeout'); // Timeout with error
289
290
// Singleton promise
291
const fetchData = createSingletonPromise(async () => {
292
const response = await fetch('/api/data');
293
return response.json();
294
});
295
296
// Multiple calls share same promise instance
297
const data1 = await fetchData(); // Makes API call
298
const data2 = await fetchData(); // Uses same promise
299
const data3 = await fetchData(); // Uses same promise
300
301
// Reset for new calls
302
await fetchData.reset();
303
const newData = await fetchData(); // Makes new API call
304
```
305
306
### Object Utilities
307
308
Utilities for object manipulation and property access.
309
310
```typescript { .api }
311
/**
312
* Check if object contains property
313
* @param obj - Object to check
314
* @param key - Property key to look for
315
* @returns Whether property exists
316
*/
317
function containsProp(obj: object, key: string): boolean;
318
319
/**
320
* Pick properties from object
321
* @param obj - Source object
322
* @param keys - Keys to pick
323
* @returns New object with picked properties
324
*/
325
function objectPick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
326
327
/**
328
* Omit properties from object
329
* @param obj - Source object
330
* @param keys - Keys to omit
331
* @returns New object with omitted properties
332
*/
333
function objectOmit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
334
335
/**
336
* Get object entries as key-value pairs
337
* @param obj - Object to get entries from
338
* @returns Array of [key, value] tuples
339
*/
340
function objectEntries<T>(obj: T): Array<[keyof T, T[keyof T]]>;
341
```
342
343
**Usage Example:**
344
345
```typescript
346
import { objectPick, objectOmit, objectEntries } from "@vueuse/shared";
347
348
const user = {
349
id: 1,
350
name: 'John',
351
email: 'john@example.com',
352
password: 'secret'
353
};
354
355
// Pick specific properties
356
const publicUser = objectPick(user, ['id', 'name', 'email']);
357
// { id: 1, name: 'John', email: 'john@example.com' }
358
359
// Omit sensitive properties
360
const safeUser = objectOmit(user, ['password']);
361
// { id: 1, name: 'John', email: 'john@example.com' }
362
363
// Get entries
364
const entries = objectEntries(user);
365
// [['id', 1], ['name', 'John'], ['email', 'john@example.com'], ['password', 'secret']]
366
```
367
368
## Core Types
369
370
```typescript { .api }
371
type Fn = () => void;
372
type AnyFn = (...args: any[]) => any;
373
type FunctionArgs<Args extends any[] = any[], Return = void> = (...args: Args) => Return;
374
type Arrayable<T> = T[] | T;
375
type ElementOf<T> = T extends (infer E)[] ? E : never;
376
type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never;
377
type Awaitable<T> = Promise<T> | T;
378
type Promisify<T> = Promise<Awaited<T>>;
379
type TimerHandle = ReturnType<typeof setTimeout> | undefined;
380
```