0
# Type Definition System
1
2
The type definition system provides core utilities for creating, extending, and managing prop type definitions in Vue Types.
3
4
## Capabilities
5
6
### Type Creation Functions
7
8
Core functions for creating Vue prop type definitions with validation and default value support.
9
10
```typescript { .api }
11
/**
12
* Creates a basic Vue type definition with isRequired and def modifiers
13
* @param name - Internal name for the type (used in error messages)
14
* @param obj - Prop options object defining the type behavior
15
* @returns VueTypeDef with basic type definition methods
16
*/
17
function toType<T = any>(name: string, obj: PropOptions<T>): VueTypeDef<T>;
18
19
/**
20
* Creates a validatable Vue type definition with validate method
21
* @param name - Internal name for the type (used in error messages)
22
* @param obj - Prop options object defining the type behavior
23
* @returns VueTypeValidableDef with validation support
24
*/
25
function toValidableType<T = any>(
26
name: string,
27
obj: PropOptions<T>
28
): VueTypeValidableDef<T>;
29
30
// Prop options interface
31
interface PropOptions<T = any, D = T> {
32
type?: PropType<T> | true | null;
33
required?: boolean;
34
default?: D | DefaultFactory<D> | null | undefined | object;
35
validator?(value: unknown, props: Record<string, unknown>): boolean;
36
}
37
```
38
39
**Usage Examples:**
40
41
```typescript
42
import { toType, toValidableType } from "vue-types";
43
44
// Basic type definition
45
const basicString = toType('customString', {
46
type: String,
47
validator: (value) => typeof value === 'string'
48
});
49
50
// Validatable type definition
51
const validatableNumber = toValidableType('customNumber', {
52
type: Number
53
});
54
55
// Using the validate method
56
const positiveNumber = validatableNumber.validate((value) => value > 0);
57
58
// Custom type with complex validation
59
const emailType = toValidableType('email', {
60
type: String,
61
validator: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
62
});
63
```
64
65
### Type Extension Function
66
67
Utility for creating new types by extending existing type definitions.
68
69
```typescript { .api }
70
/**
71
* Creates a new VueTypes type using another type as base
72
* @param name - Name of the new type
73
* @param source - Source type to extend from
74
* @param props - Additional properties to merge (optional)
75
* @returns New type definition with combined properties
76
*/
77
function fromType<T extends VueTypeDef<any>>(
78
name: string,
79
source: T
80
): T;
81
82
function fromType<
83
T extends VueTypeDef<any>,
84
V extends PropOptions<InferType<T>>
85
>(
86
name: string,
87
source: T,
88
props: V
89
): Omit<T, keyof V> & V;
90
91
// Type inference helper
92
type InferType<T> = T extends VueTypeDef<infer V> ? V : T;
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
import { fromType, string, number } from "vue-types";
99
100
// Extend existing string type
101
const trimmedString = fromType('trimmedString', string(), {
102
validator: (value) => value.trim() === value
103
});
104
105
// Extend with additional properties
106
const positiveInteger = fromType('positiveInteger', number(), {
107
validator: (value) => Number.isInteger(value) && value > 0
108
});
109
110
// Chain extensions
111
const emailString = fromType('email', string(), {
112
validator: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
113
});
114
115
const requiredEmail = fromType('requiredEmail', emailString, {
116
required: true
117
});
118
```
119
120
### Type Validation Function
121
122
Function for validating values against prop type definitions at runtime.
123
124
```typescript { .api }
125
/**
126
* Validates a given value against a prop type object
127
* @param type - Type definition or constructor to validate against
128
* @param value - Value to check for validity
129
* @param silent - If true, returns error string instead of logging warnings
130
* @returns true if valid, false if invalid (or error string in silent mode)
131
*/
132
function validateType<T, U>(
133
type: T,
134
value: U,
135
silent?: false
136
): boolean;
137
138
function validateType<T, U>(
139
type: T,
140
value: U,
141
silent: true
142
): string | boolean;
143
```
144
145
**Usage Examples:**
146
147
```typescript
148
import { validateType, string, number, shape } from "vue-types";
149
150
// Basic validation
151
const isValidString = validateType(string(), "hello"); // true
152
const isValidNumber = validateType(number(), "hello"); // false
153
154
// Silent mode for error details
155
const result = validateType(number(), "hello", true);
156
if (typeof result === 'string') {
157
console.log('Validation error:', result);
158
}
159
160
// Complex type validation
161
const userType = shape({
162
name: string().isRequired,
163
age: number()
164
});
165
166
const validUser = { name: "John", age: 30 };
167
const invalidUser = { name: "", age: "thirty" };
168
169
console.log(validateType(userType, validUser)); // true
170
console.log(validateType(userType, invalidUser)); // false
171
172
// Validate with context
173
const customType = {
174
validator: (value, props) => props.strict ? value > 100 : value > 0
175
};
176
177
validateType(customType, 50); // Depends on props context
178
```
179
180
### VueTypes Factory Function
181
182
Factory function for creating custom VueTypes classes with predefined default values.
183
184
```typescript { .api }
185
/**
186
* Creates a new VueTypes class with custom default values
187
* @param defs - Partial default values for sensible defaults
188
* @returns New VueTypes class constructor with specified defaults
189
*/
190
function createTypes(defs?: Partial<VueTypesDefaults>): VueTypesInterface;
191
192
// Default values interface
193
interface VueTypesDefaults {
194
func: (...args: any[]) => any;
195
bool: boolean;
196
string: string;
197
number: number;
198
array: () => any[];
199
object: () => Record<string, any>;
200
integer: number;
201
}
202
203
// VueTypes interface
204
type VueTypesInterface = ReturnType<typeof createTypes>;
205
```
206
207
**Usage Examples:**
208
209
```typescript
210
import { createTypes } from "vue-types";
211
212
// Create VueTypes with custom defaults
213
const MyVueTypes = createTypes({
214
string: 'Default text',
215
number: -1,
216
bool: false,
217
array: () => ['default', 'items'],
218
object: () => ({ initialized: true })
219
});
220
221
// Use custom defaults
222
const titleProp = MyVueTypes.string; // Has default: 'Default text'
223
const countProp = MyVueTypes.number; // Has default: -1
224
const activeProp = MyVueTypes.bool; // Has default: false
225
226
// Create context-specific VueTypes
227
const ApiVueTypes = createTypes({
228
string: '',
229
number: 0,
230
array: () => [],
231
object: () => ({})
232
});
233
234
// Multiple instances with different defaults
235
const FormVueTypes = createTypes({
236
string: '',
237
bool: false,
238
number: 0
239
});
240
241
const GameVueTypes = createTypes({
242
number: 1,
243
bool: true,
244
array: () => []
245
});
246
```
247
248
## Type Definition Interfaces
249
250
Core interfaces that define the structure and behavior of Vue type definitions.
251
252
```typescript { .api }
253
// Base type definition interface
254
interface VueTypeBaseDef<T = unknown, D = DefaultType<T>, U = T>
255
extends PropOptions<T> {
256
_vueTypes_name: string;
257
type?: PropType<T>;
258
readonly def: (def?: D) => this & { default: U };
259
readonly isRequired: this & { required: true };
260
}
261
262
// Basic type definition (non-validatable)
263
interface VueTypeDef<T = unknown> extends VueTypeBaseDef<T> {}
264
265
// Validatable type definition with validate method
266
interface VueTypeValidableDef<T = unknown, V = ValidatorFunction<T>>
267
extends VueTypeBaseDef<T> {
268
readonly validate: (fn: V) => this & { validator: V };
269
}
270
271
// Shape-specific interfaces
272
interface VueTypeShape<T> extends VueTypeBaseDef<T> {
273
readonly loose: VueTypeLooseShape<T>;
274
}
275
276
interface VueTypeLooseShape<T> extends VueTypeBaseDef<T> {
277
readonly loose: VueTypeLooseShape<T>;
278
readonly _vueTypes_isLoose: true;
279
}
280
281
// Utility types
282
type ValidatorFunction<T> = (
283
value: T,
284
props?: Record<string, unknown>
285
) => boolean;
286
287
type DefaultType<T> = T extends NativeType ? T : DefaultFactory<T>;
288
type DefaultFactory<T> = (() => T) | T;
289
type NativeType = string | boolean | number | null | undefined | Function;
290
```
291
292
## Advanced Usage Patterns
293
294
### Custom Type Builders
295
296
Create reusable type builders for common patterns:
297
298
```typescript
299
import { toValidableType, validateType } from "vue-types";
300
301
// URL type builder
302
function createUrlType(name: string) {
303
return toValidableType<string>(name, {
304
type: String,
305
validator: (value) => {
306
try {
307
new URL(value);
308
return true;
309
} catch {
310
return false;
311
}
312
}
313
});
314
}
315
316
// Range type builder
317
function createRangeType(name: string, min: number, max: number) {
318
return toValidableType<number>(name, {
319
type: Number,
320
validator: (value) => value >= min && value <= max
321
});
322
}
323
324
// Usage
325
const urlProp = createUrlType('websiteUrl');
326
const percentageProp = createRangeType('percentage', 0, 100);
327
```
328
329
### Composite Validation
330
331
Combine multiple validation functions for complex requirements:
332
333
```typescript
334
import { fromType, string } from "vue-types";
335
336
// Create base types
337
const nonEmptyString = fromType('nonEmpty', string(), {
338
validator: (value) => value.length > 0
339
});
340
341
const trimmedString = fromType('trimmed', nonEmptyString, {
342
validator: (value) => value.trim() === value
343
});
344
345
const alphanumericString = fromType('alphanumeric', trimmedString, {
346
validator: (value) => /^[a-zA-Z0-9]+$/.test(value)
347
});
348
349
// Final validated type combines all requirements
350
const usernameType = fromType('username', alphanumericString, {
351
validator: (value) => value.length >= 3 && value.length <= 20
352
});
353
```
354
355
### Type Utilities Integration
356
357
Use type system utilities with Vue components:
358
359
```typescript
360
import { createTypes, validateType } from "vue-types";
361
362
// Create domain-specific types
363
const ApiTypes = createTypes({
364
string: '',
365
number: 0,
366
bool: false
367
});
368
369
// Component with validation helpers
370
export default {
371
props: {
372
endpoint: ApiTypes.string.isRequired,
373
timeout: ApiTypes.number.def(5000),
374
retries: ApiTypes.number.validate((value) => value >= 0).def(3)
375
},
376
377
methods: {
378
validateEndpoint(url: string) {
379
return validateType(ApiTypes.string, url, true);
380
},
381
382
isValidTimeout(ms: number) {
383
return validateType(
384
ApiTypes.number.validate((value) => value > 0),
385
ms
386
);
387
}
388
}
389
};
390
```
391
392
### Runtime Type Checking
393
394
Leverage the type system for runtime validation beyond props:
395
396
```typescript
397
import { validateType, shape, string, number, arrayOf } from "vue-types";
398
399
// Define API response shape
400
const apiResponseType = shape({
401
data: arrayOf(shape({
402
id: number().isRequired,
403
name: string().isRequired,
404
email: string()
405
})),
406
status: string().isRequired,
407
message: string()
408
});
409
410
// Validate API responses
411
async function fetchUsers() {
412
const response = await fetch('/api/users');
413
const data = await response.json();
414
415
// Runtime validation
416
const isValid = validateType(apiResponseType, data, true);
417
if (typeof isValid === 'string') {
418
throw new Error(`Invalid API response: ${isValid}`);
419
}
420
421
return data;
422
}
423
```