Prop type definitions for Vue.js components with runtime validation and TypeScript support
—
Configuration options and utility functions for customizing Vue Types behavior, validation settings, and accessing internal functionality.
Global configuration object that controls warning behavior and logging throughout Vue Types.
/**
* Global configuration object for Vue Types behavior
*/
const config: VueTypesConfig;
interface VueTypesConfig {
/** Suppress all validation warnings when true */
silent: boolean;
/** Console method to use for warnings */
logLevel: 'log' | 'warn' | 'error' | 'debug' | 'info';
}Usage Examples:
import { config } from "vue-types";
// Suppress all warnings
config.silent = true;
// Change warning level
config.logLevel = 'error';
// Development vs production settings
if (process.env.NODE_ENV === 'production') {
config.silent = true;
} else {
config.silent = false;
config.logLevel = 'warn';
}
// Temporarily disable warnings
const originalSilent = config.silent;
config.silent = true;
// ... perform operations without warnings
config.silent = originalSilent;Utility methods available on the VueTypes class for validation and type creation.
/**
* Utility methods accessible via VueTypes.utils
*/
static utils: {
/**
* Validate a value against a type definition
* @param value - Value to validate
* @param type - Type definition to validate against
* @returns true if value matches type, false otherwise
*/
validate<T, U>(value: T, type: U): boolean;
/**
* Create a type definition with optional validation support
* @param name - Internal name for the type
* @param obj - Prop options defining the type
* @param validable - Whether to include validate() method
* @returns VueTypeDef or VueTypeValidableDef based on validable parameter
*/
toType<T = unknown, Validable extends boolean = false>(
name: string,
obj: PropOptions<T>,
validable?: Validable
): Validable extends true ? VueTypeValidableDef<T> : VueTypeDef<T>;
};Usage Examples:
import VueTypes from "vue-types";
// Validate values using utils
const isValidString = VueTypes.utils.validate("hello", VueTypes.string);
const isValidNumber = VueTypes.utils.validate(42, VueTypes.number);
console.log(isValidString); // true
console.log(isValidNumber); // true
// Create custom types using utils
const customStringType = VueTypes.utils.toType('customString', {
type: String,
validator: (value) => value.length > 0
});
const validatableCustomType = VueTypes.utils.toType('validatableCustom', {
type: Number
}, true);
// Use the validatable version
const positiveNumber = validatableCustomType.validate((value) => value > 0);System for managing sensible default values across all Vue Types validators.
/**
* Interface defining default values for each validator type
*/
interface VueTypesDefaults {
/** Default function for func validator */
func: (...args: any[]) => any;
/** Default boolean value for bool validator */
bool: boolean;
/** Default string value for string validator */
string: string;
/** Default number value for number validator */
number: number;
/** Default array factory for array validator */
array: () => any[];
/** Default object factory for object validator */
object: () => Record<string, any>;
/** Default number value for integer validator */
integer: number;
}
/**
* VueTypes static properties for managing defaults
*/
static defaults: Partial<VueTypesDefaults>;
static get sensibleDefaults(): Partial<VueTypesDefaults>;
static set sensibleDefaults(v: boolean | Partial<VueTypesDefaults>);Usage Examples:
import VueTypes from "vue-types";
// View current defaults
console.log(VueTypes.defaults);
console.log(VueTypes.sensibleDefaults);
// Modify defaults
VueTypes.defaults.string = 'Custom default';
VueTypes.defaults.number = -1;
VueTypes.defaults.bool = false;
// Now all validators use custom defaults
const title = VueTypes.string; // default: 'Custom default'
const count = VueTypes.number; // default: -1
const active = VueTypes.bool; // default: false
// Reset to sensible defaults
VueTypes.sensibleDefaults = true;
// Disable defaults completely
VueTypes.sensibleDefaults = false;
// Set custom defaults via sensibleDefaults
VueTypes.sensibleDefaults = {
string: '',
number: 0,
bool: true,
array: () => [],
object: () => ({}),
func: () => undefined,
integer: 0
};Lightweight production version that disables runtime validation for performance.
/**
* Production shim export that provides the same API with disabled validation
* Import from 'vue-types/shim' for production builds
*/
// All validators return basic prop definitions without runtime validation
// Configuration and utilities are preserved but validation is no-op
function validateType<T, U>(type: T, value: U, silent?: boolean): boolean {
return true; // Always returns true in shim
}Usage Examples:
// webpack.config.js or similar bundler configuration
module.exports = {
resolve: {
alias: {
'vue-types': process.env.NODE_ENV === 'production'
? 'vue-types/shim'
: 'vue-types'
}
}
};
// Component code remains the same
import VueTypes from "vue-types";
export default {
props: {
// In production: no runtime validation
// In development: full validation
title: VueTypes.string.isRequired,
count: VueTypes.number.def(0)
}
};
// Manual shim usage
import VueTypes from "vue-types/shim";
const titleProp = VueTypes.string.isRequired; // No runtime validationAdditional utility functions available for internal operations and advanced usage.
/**
* Utility functions for internal operations
*/
// Type checking utilities (internal)
function isVueTypeDef<T>(value: any, name?: string): value is VueTypeDef<T>;
function isComplexType<T>(value: any): value is VueProp<T>;
function isFunction<T extends Function>(value: unknown): value is T;
function isArray(value: unknown): value is any[];
function isInteger(value: unknown): value is number;
// Object utilities (internal)
function deepClone<T>(input: T): T;
function has<T, U extends keyof T>(obj: T, prop: U): boolean;
// Warning system (internal)
function warn(msg: string, level?: VueTypesConfig['logLevel']): void;Usage Examples:
// These are typically internal utilities, but can be imported for advanced usage
import {
isVueTypeDef,
isComplexType,
deepClone,
warn
} from "vue-types";
// Check if a value is a VueTypes definition
const stringType = VueTypes.string;
const isTypeDef = isVueTypeDef(stringType); // true
const isStringTypeDef = isVueTypeDef(stringType, 'string'); // true
// Check if a value is a complex prop type
const isComplex = isComplexType({ type: String, required: true }); // true
// Deep clone objects (used internally for default values)
const originalArray = [{ name: 'John' }, { name: 'Jane' }];
const clonedArray = deepClone(originalArray);
// Manual warning (respects global config)
warn('Custom validation warning');
warn('Error level warning', 'error');Configure Vue Types behavior based on environment:
import { config } from "vue-types";
// Environment-based configuration
function configureVueTypes() {
if (process.env.NODE_ENV === 'production') {
// Production: silent warnings for performance
config.silent = true;
} else if (process.env.NODE_ENV === 'test') {
// Testing: use error level for test failures
config.silent = false;
config.logLevel = 'error';
} else {
// Development: full warnings
config.silent = false;
config.logLevel = 'warn';
}
}
configureVueTypes();Create multiple VueTypes instances for different contexts:
import { createTypes } from "vue-types";
// API-specific types with empty defaults
const ApiTypes = createTypes({
string: '',
number: 0,
bool: false,
array: () => [],
object: () => ({})
});
// Form-specific types with sensible form defaults
const FormTypes = createTypes({
string: '',
number: 0,
bool: false,
array: () => [],
object: () => ({})
});
// Game-specific types with game-appropriate defaults
const GameTypes = createTypes({
string: 'Player',
number: 1,
bool: true,
array: () => [0, 0, 0],
object: () => ({ x: 0, y: 0 })
});
// Use context-appropriate types
const ApiComponent = {
props: {
endpoint: ApiTypes.string.isRequired,
data: ApiTypes.object.def(() => ({}))
}
};
const FormComponent = {
props: {
placeholder: FormTypes.string.def('Enter text...'),
required: FormTypes.bool.def(false)
}
};Use utilities for debugging validation issues:
import VueTypes, { validateType, config } from "vue-types";
// Debug validation function
function debugValidation(type: any, value: any, context: string) {
// Temporarily enable detailed logging
const originalSilent = config.silent;
const originalLevel = config.logLevel;
config.silent = false;
config.logLevel = 'warn';
console.group(`Validation Debug: ${context}`);
console.log('Type:', type);
console.log('Value:', value);
const result = validateType(type, value, true);
if (typeof result === 'string') {
console.error('Validation Error:', result);
} else {
console.log('Validation Result:', result);
}
console.groupEnd();
// Restore original settings
config.silent = originalSilent;
config.logLevel = originalLevel;
return result;
}
// Usage in component
export default {
props: {
user: VueTypes.shape({
name: VueTypes.string.isRequired,
age: VueTypes.number
}).isRequired
},
created() {
// Debug prop validation
debugValidation(this.$options.props.user, this.user, 'User Prop');
}
};Monitor validation performance in development:
import { config, validateType } from "vue-types";
// Wrapper for performance monitoring
function performanceValidateType(type: any, value: any, silent = false) {
if (config.silent) {
return true; // Skip validation entirely if silent
}
const start = performance.now();
const result = validateType(type, value, silent);
const end = performance.now();
if (end - start > 1) { // Log slow validations
console.warn(`Slow validation (${(end - start).toFixed(2)}ms):`, type._vueTypes_name || 'unknown');
}
return result;
}
// Use in performance-critical components
const fastValidation = performanceValidateType(VueTypes.string, 'test');Install with Tessl CLI
npx tessl i tessl/npm-vue-types