TypeScript Runtime Validator Typia Technical Documentation
Overview
Typia is a high-performance runtime type validation library for TypeScript. It operates solely on pure TypeScript type definitions, eliminating the need for additional schema definitions unlike other validation libraries. It offers up to 20,000 times faster performance and can perfectly validate complex union types.
Installation and Configuration
The following configuration is required in tsconfig.json:
{
"compilerOptions": {
"plugins": [
{
"transform": "typia/lib/transform"
}
]
}
}
Core Validators
Assert Validator
- Purpose: Validates the type of a value and throws a TypeGuardError for incorrect types
- Syntax:
typia.assert<T>(input: unknown): T
- Error Handling: Provides method, path, expected, and value information through TypeGuardError
- Features: Allows additional properties and validates basic types and built-in classes (Date, Map, etc.)
Is Validator
- Purpose: Checks if a value matches the specified type
- Syntax:
typia.is<T>(input: unknown): boolean
- Return: Returns true if the type matches, false otherwise
- Usage: Used for type checking in conditional statements
Validate Validator
- Purpose: Validates value and provides detailed results
- Syntax:
typia.validate<T>(input: unknown): ValidationResult
- Result Structure: Includes success/failure status and error information
- Error Handling: Allows checking all validation errors at once
Performance Considerations
- Shows up to 20,000 times faster performance compared to competing libraries like TypeBox, ajv, io-ts, zod, and class-validator
- Fully supports advanced TypeScript features including complex union types, recursive types, and template literal types
Best Practices
- Create reusable validation functions using
createAssert
,createIs
, andcreateValidate
functions - Separate instanceof checks are required for custom class validation
- Function type validation requires enabling the functional setting in tsconfig.json plugin options
Integration Example
interface IMember {
id: string & tags.Format<"uuid">;
email: string & tags.Format<"email">;
age: number & tags.Type<"uint32"> & tags.ExclusiveMinimum<19> & tags.Maximum<100>;
}
const assertMember = typia.createAssert<IMember>();
assertMember({
id: "550e8400-e29b-41d4-a716-446655440000",
email: "example@email.com",
age: 25
});
References
- Official Documentation: https://typia.io/docs/validators/assert/
- Validator Documentation:
Conclusion
Typia is the optimal runtime type validation tool that ensures type safety while providing outstanding performance in TypeScript projects. It operates solely on pure TypeScript types and features comprehensive support for complex types.
Top comments (0)