Class

TypeValidator

TypeValidator(messageopt)

Constructor

# new TypeValidator(messageopt)

The TypeValidator ensures that a value matches one of the specified types. It can validate against a single type, multiple types, or a type with a specific name. This validator is typically used with the @type decorator and is fundamental for ensuring type safety in validated models.

Validator for checking if a value is of the expected type(s)

sequenceDiagram participant C as Client participant V as TypeValidator participant R as Reflection C->>V: new TypeValidator(message) C->>V: hasErrors(value, options) alt value is undefined V-->>C: undefined (valid) else value is defined V->>R: evaluateDesignTypes(value, types) alt type evaluation passes V-->>C: undefined (valid) else type evaluation fails V->>V: Format error message with type info V-->>C: Error message end end
Parameters:
Name Type Attributes Description
message string <optional>

Custom error message to display when validation fails, defaults to DEFAULT_ERROR_MESSAGES#TYPE

View Source validation/Validators/TypeValidator.ts, line 14

Example
```typescript
// Create a type validator with default error message
const typeValidator = new TypeValidator();

// Create a type validator with custom error message
const customTypeValidator = new TypeValidator("Value must be of type {0}, but got {1}");

// Validate against a single type
const stringOptions = { types: "string" };
typeValidator.hasErrors("hello", stringOptions); // undefined (valid)
typeValidator.hasErrors(123, stringOptions); // Returns error message (invalid)

// Validate against multiple types
const multiOptions = { types: ["string", "number"] };
typeValidator.hasErrors("hello", multiOptions); // undefined (valid)
typeValidator.hasErrors(123, multiOptions); // undefined (valid)
typeValidator.hasErrors(true, multiOptions); // Returns error message (invalid)

// Validate against a class type
const classOptions = { types: { name: "Date" } };
typeValidator.hasErrors(new Date(), classOptions); // undefined (valid)
```

Extends

Methods

# hasErrors(value, options) → {string|undefined}

Validates that the provided value matches one of the specified types. It uses the Reflection utility to evaluate if the value's type matches the expected types. The method skips validation for undefined values to avoid conflicts with the RequiredValidator.

Checks if a value is of the expected type(s)

Parameters:
Name Type Description
value any

The value to validate

options TypeValidatorOptions

Configuration options containing the expected types

Overrides:
See:

View Source validation/Validators/TypeValidator.ts, line 146

Error message if validation fails, undefined if validation passes

string | undefined