Skip to main content

index/interfaces/ValidationResult.md

Standard validation result

Provides consistent interface for all validators with proper TypeScript strict mode compatibility.

Design Rationale​

This interface uses explicit T | undefined instead of optional properties to ensure compatibility with TypeScript's exactOptionalPropertyTypes setting.

TypeScript Configuration Context​

// tsconfig.json
{
"compilerOptions": {
"exactOptionalPropertyTypes": true
}
}

With exactOptionalPropertyTypes: true, TypeScript strictly enforces that optional properties (property?: Type) cannot be assigned undefined values. Only missing properties are allowed.

Interface Design Choice​

// ❌ INCORRECT - Breaks with exactOptionalPropertyTypes
interface ValidationResult<T> {
success: boolean;
data?: T; // Optional property
errors?: string[]; // Optional property
}

// ✅ CORRECT - Compatible with exactOptionalPropertyTypes
interface ValidationResult<T> {
success: boolean;
data: T | undefined; // Explicit undefined
errors: string[] | undefined; // Explicit undefined
}

Usage Patterns​

// Success case
const successResult: ValidationResult<string> = {
success: true,
data: 'validated-value',
errors: undefined
};

// Failure case
const failureResult: ValidationResult<string> = {
success: false,
data: undefined,
errors: ['Validation error message']
};

// Type-safe consumption
function handleResult(result: ValidationResult<string>) {
if (result.success) {
// TypeScript knows result.data is string | undefined
console.log(result.data);
} else {
// TypeScript knows result.errors is string[] | undefined
console.error(result.errors);
}
}

Benefits​

  1. Type Safety: Explicit undefined makes intent clear
  2. Strict Mode: Compatible with exactOptionalPropertyTypes
  3. Consistency: All validators return same shape
  4. Backward Compatibility: Maintains existing API surface

Type Parameters​

Type ParameterDescription
TThe type of the validated data

Properties​

PropertyTypeDescription
dataT | undefinedValidated and transformed data (if successful)
errorsstring[] | undefinedValidation error messages (if failed)
successbooleanWhether validation passed