0
# Configuration & Utilities
1
2
Configuration options and utility functions for customizing Vue Types behavior, validation settings, and accessing internal functionality.
3
4
## Capabilities
5
6
### Global Configuration
7
8
Global configuration object that controls warning behavior and logging throughout Vue Types.
9
10
```typescript { .api }
11
/**
12
* Global configuration object for Vue Types behavior
13
*/
14
const config: VueTypesConfig;
15
16
interface VueTypesConfig {
17
/** Suppress all validation warnings when true */
18
silent: boolean;
19
/** Console method to use for warnings */
20
logLevel: 'log' | 'warn' | 'error' | 'debug' | 'info';
21
}
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { config } from "vue-types";
28
29
// Suppress all warnings
30
config.silent = true;
31
32
// Change warning level
33
config.logLevel = 'error';
34
35
// Development vs production settings
36
if (process.env.NODE_ENV === 'production') {
37
config.silent = true;
38
} else {
39
config.silent = false;
40
config.logLevel = 'warn';
41
}
42
43
// Temporarily disable warnings
44
const originalSilent = config.silent;
45
config.silent = true;
46
// ... perform operations without warnings
47
config.silent = originalSilent;
48
```
49
50
### VueTypes Static Utilities
51
52
Utility methods available on the VueTypes class for validation and type creation.
53
54
```typescript { .api }
55
/**
56
* Utility methods accessible via VueTypes.utils
57
*/
58
static utils: {
59
/**
60
* Validate a value against a type definition
61
* @param value - Value to validate
62
* @param type - Type definition to validate against
63
* @returns true if value matches type, false otherwise
64
*/
65
validate<T, U>(value: T, type: U): boolean;
66
67
/**
68
* Create a type definition with optional validation support
69
* @param name - Internal name for the type
70
* @param obj - Prop options defining the type
71
* @param validable - Whether to include validate() method
72
* @returns VueTypeDef or VueTypeValidableDef based on validable parameter
73
*/
74
toType<T = unknown, Validable extends boolean = false>(
75
name: string,
76
obj: PropOptions<T>,
77
validable?: Validable
78
): Validable extends true ? VueTypeValidableDef<T> : VueTypeDef<T>;
79
};
80
```
81
82
**Usage Examples:**
83
84
```typescript
85
import VueTypes from "vue-types";
86
87
// Validate values using utils
88
const isValidString = VueTypes.utils.validate("hello", VueTypes.string);
89
const isValidNumber = VueTypes.utils.validate(42, VueTypes.number);
90
91
console.log(isValidString); // true
92
console.log(isValidNumber); // true
93
94
// Create custom types using utils
95
const customStringType = VueTypes.utils.toType('customString', {
96
type: String,
97
validator: (value) => value.length > 0
98
});
99
100
const validatableCustomType = VueTypes.utils.toType('validatableCustom', {
101
type: Number
102
}, true);
103
104
// Use the validatable version
105
const positiveNumber = validatableCustomType.validate((value) => value > 0);
106
```
107
108
### Default Values System
109
110
System for managing sensible default values across all Vue Types validators.
111
112
```typescript { .api }
113
/**
114
* Interface defining default values for each validator type
115
*/
116
interface VueTypesDefaults {
117
/** Default function for func validator */
118
func: (...args: any[]) => any;
119
/** Default boolean value for bool validator */
120
bool: boolean;
121
/** Default string value for string validator */
122
string: string;
123
/** Default number value for number validator */
124
number: number;
125
/** Default array factory for array validator */
126
array: () => any[];
127
/** Default object factory for object validator */
128
object: () => Record<string, any>;
129
/** Default number value for integer validator */
130
integer: number;
131
}
132
133
/**
134
* VueTypes static properties for managing defaults
135
*/
136
static defaults: Partial<VueTypesDefaults>;
137
138
static get sensibleDefaults(): Partial<VueTypesDefaults>;
139
static set sensibleDefaults(v: boolean | Partial<VueTypesDefaults>);
140
```
141
142
**Usage Examples:**
143
144
```typescript
145
import VueTypes from "vue-types";
146
147
// View current defaults
148
console.log(VueTypes.defaults);
149
console.log(VueTypes.sensibleDefaults);
150
151
// Modify defaults
152
VueTypes.defaults.string = 'Custom default';
153
VueTypes.defaults.number = -1;
154
VueTypes.defaults.bool = false;
155
156
// Now all validators use custom defaults
157
const title = VueTypes.string; // default: 'Custom default'
158
const count = VueTypes.number; // default: -1
159
const active = VueTypes.bool; // default: false
160
161
// Reset to sensible defaults
162
VueTypes.sensibleDefaults = true;
163
164
// Disable defaults completely
165
VueTypes.sensibleDefaults = false;
166
167
// Set custom defaults via sensibleDefaults
168
VueTypes.sensibleDefaults = {
169
string: '',
170
number: 0,
171
bool: true,
172
array: () => [],
173
object: () => ({}),
174
func: () => undefined,
175
integer: 0
176
};
177
```
178
179
### Production Shim
180
181
Lightweight production version that disables runtime validation for performance.
182
183
```typescript { .api }
184
/**
185
* Production shim export that provides the same API with disabled validation
186
* Import from 'vue-types/shim' for production builds
187
*/
188
189
// All validators return basic prop definitions without runtime validation
190
// Configuration and utilities are preserved but validation is no-op
191
function validateType<T, U>(type: T, value: U, silent?: boolean): boolean {
192
return true; // Always returns true in shim
193
}
194
```
195
196
**Usage Examples:**
197
198
```typescript
199
// webpack.config.js or similar bundler configuration
200
module.exports = {
201
resolve: {
202
alias: {
203
'vue-types': process.env.NODE_ENV === 'production'
204
? 'vue-types/shim'
205
: 'vue-types'
206
}
207
}
208
};
209
210
// Component code remains the same
211
import VueTypes from "vue-types";
212
213
export default {
214
props: {
215
// In production: no runtime validation
216
// In development: full validation
217
title: VueTypes.string.isRequired,
218
count: VueTypes.number.def(0)
219
}
220
};
221
222
// Manual shim usage
223
import VueTypes from "vue-types/shim";
224
const titleProp = VueTypes.string.isRequired; // No runtime validation
225
```
226
227
### Utility Functions
228
229
Additional utility functions available for internal operations and advanced usage.
230
231
```typescript { .api }
232
/**
233
* Utility functions for internal operations
234
*/
235
236
// Type checking utilities (internal)
237
function isVueTypeDef<T>(value: any, name?: string): value is VueTypeDef<T>;
238
function isComplexType<T>(value: any): value is VueProp<T>;
239
function isFunction<T extends Function>(value: unknown): value is T;
240
function isArray(value: unknown): value is any[];
241
function isInteger(value: unknown): value is number;
242
243
// Object utilities (internal)
244
function deepClone<T>(input: T): T;
245
function has<T, U extends keyof T>(obj: T, prop: U): boolean;
246
247
// Warning system (internal)
248
function warn(msg: string, level?: VueTypesConfig['logLevel']): void;
249
```
250
251
**Usage Examples:**
252
253
```typescript
254
// These are typically internal utilities, but can be imported for advanced usage
255
import {
256
isVueTypeDef,
257
isComplexType,
258
deepClone,
259
warn
260
} from "vue-types";
261
262
// Check if a value is a VueTypes definition
263
const stringType = VueTypes.string;
264
const isTypeDef = isVueTypeDef(stringType); // true
265
const isStringTypeDef = isVueTypeDef(stringType, 'string'); // true
266
267
// Check if a value is a complex prop type
268
const isComplex = isComplexType({ type: String, required: true }); // true
269
270
// Deep clone objects (used internally for default values)
271
const originalArray = [{ name: 'John' }, { name: 'Jane' }];
272
const clonedArray = deepClone(originalArray);
273
274
// Manual warning (respects global config)
275
warn('Custom validation warning');
276
warn('Error level warning', 'error');
277
```
278
279
## Advanced Configuration Patterns
280
281
### Environment-Specific Configuration
282
283
Configure Vue Types behavior based on environment:
284
285
```typescript
286
import { config } from "vue-types";
287
288
// Environment-based configuration
289
function configureVueTypes() {
290
if (process.env.NODE_ENV === 'production') {
291
// Production: silent warnings for performance
292
config.silent = true;
293
} else if (process.env.NODE_ENV === 'test') {
294
// Testing: use error level for test failures
295
config.silent = false;
296
config.logLevel = 'error';
297
} else {
298
// Development: full warnings
299
config.silent = false;
300
config.logLevel = 'warn';
301
}
302
}
303
304
configureVueTypes();
305
```
306
307
### Context-Specific VueTypes
308
309
Create multiple VueTypes instances for different contexts:
310
311
```typescript
312
import { createTypes } from "vue-types";
313
314
// API-specific types with empty defaults
315
const ApiTypes = createTypes({
316
string: '',
317
number: 0,
318
bool: false,
319
array: () => [],
320
object: () => ({})
321
});
322
323
// Form-specific types with sensible form defaults
324
const FormTypes = createTypes({
325
string: '',
326
number: 0,
327
bool: false,
328
array: () => [],
329
object: () => ({})
330
});
331
332
// Game-specific types with game-appropriate defaults
333
const GameTypes = createTypes({
334
string: 'Player',
335
number: 1,
336
bool: true,
337
array: () => [0, 0, 0],
338
object: () => ({ x: 0, y: 0 })
339
});
340
341
// Use context-appropriate types
342
const ApiComponent = {
343
props: {
344
endpoint: ApiTypes.string.isRequired,
345
data: ApiTypes.object.def(() => ({}))
346
}
347
};
348
349
const FormComponent = {
350
props: {
351
placeholder: FormTypes.string.def('Enter text...'),
352
required: FormTypes.bool.def(false)
353
}
354
};
355
```
356
357
### Validation Debugging
358
359
Use utilities for debugging validation issues:
360
361
```typescript
362
import VueTypes, { validateType, config } from "vue-types";
363
364
// Debug validation function
365
function debugValidation(type: any, value: any, context: string) {
366
// Temporarily enable detailed logging
367
const originalSilent = config.silent;
368
const originalLevel = config.logLevel;
369
370
config.silent = false;
371
config.logLevel = 'warn';
372
373
console.group(`Validation Debug: ${context}`);
374
console.log('Type:', type);
375
console.log('Value:', value);
376
377
const result = validateType(type, value, true);
378
379
if (typeof result === 'string') {
380
console.error('Validation Error:', result);
381
} else {
382
console.log('Validation Result:', result);
383
}
384
385
console.groupEnd();
386
387
// Restore original settings
388
config.silent = originalSilent;
389
config.logLevel = originalLevel;
390
391
return result;
392
}
393
394
// Usage in component
395
export default {
396
props: {
397
user: VueTypes.shape({
398
name: VueTypes.string.isRequired,
399
age: VueTypes.number
400
}).isRequired
401
},
402
403
created() {
404
// Debug prop validation
405
debugValidation(this.$options.props.user, this.user, 'User Prop');
406
}
407
};
408
```
409
410
### Performance Monitoring
411
412
Monitor validation performance in development:
413
414
```typescript
415
import { config, validateType } from "vue-types";
416
417
// Wrapper for performance monitoring
418
function performanceValidateType(type: any, value: any, silent = false) {
419
if (config.silent) {
420
return true; // Skip validation entirely if silent
421
}
422
423
const start = performance.now();
424
const result = validateType(type, value, silent);
425
const end = performance.now();
426
427
if (end - start > 1) { // Log slow validations
428
console.warn(`Slow validation (${(end - start).toFixed(2)}ms):`, type._vueTypes_name || 'unknown');
429
}
430
431
return result;
432
}
433
434
// Use in performance-critical components
435
const fastValidation = performanceValidateType(VueTypes.string, 'test');
436
```