Skip to Content

validate() function

undefined

export function validate<T>(input: T): IValidation<T>; export function validate<T>(input: unknown): IValidation<T>;

Validates a value type.

typia.validate<T>() function validates input value type, and archives every type errors detaily into IValidation.IFailure.errors array, when the input value is not following the promised type T. Of course, if the parametric input value is following the type T, IValidation.ISuccess instance would be returned.

In the below example case, as id and age values are different with its definition of IMember, such errors would be archived into the IValidation.IFailure.errors array.

  • errors[0]
    • path: input.id
    • expected: string & Format<"uuid">
    • value: 5
  • errors[1]
    • path: input.age
    • expected: number & Format<"uint32">
    • value: 20.75

examples/src/validators/validate.ts
import typia, { tags } from "typia"; const res: typia.IValidation<IMember> = typia.validate<IMember>({ id: 5, // wrong, must be string (uuid) age: 20.75, // wrong, not integer email: "samchon.github@gmail.com", }); if (res.success === false) console.log(res.errors); interface IMember { id: string & tags.Format<"uuid">; email: string & tags.Format<"email">; age: number & tags.Type<"uint32"> & tags.ExclusiveMinimum<19> & tags.Maximum<100>; }

validateEquals() function

export function validateEquals<T>(input: T): IValidation<T>; export function validateEquals<T>(input: unknown): IValidation<T>;

More strict validate function prohibiting superfluous properties.

typia.validate<T> function detects every type errors of input value, however, it can’t detect superfluous properties. If you want to prohibit those superfluous properties, so that archive them into IValidation.IFailure.errors array, use typia.validateEquals<T>() function instead.

In the below example case, as id property is different with its type definition and sex property is not defined in the IMember type, such errors would be archived into the IValidation.IFailure.errors array:

  • errors[0]
    • path: input.id
    • expected: string (@format uuid)
    • value: something
  • errors[1]
    • path: input.sex
    • expected: undefined
    • value: 1
examples/src/validators/validateEquals.ts
import typia, { tags } from "typia"; const res: typia.IValidation<IMember> = typia.validateEquals<IMember>({ age: 30, email: "samchon.github@gmail.com", id: "something", // wrong, must be string (uuid) sex: 1, // extra property }); if (res.success === false) console.log(res.errors); interface IMember { id: string & tags.Format<"uuid">; email: string & tags.Format<"email">; age: number & tags.Type<"uint32"> & tags.ExclusiveMinimum<19> & tags.Maximum<100>; }

Reusable functions

export function createValidate<T> = (input: unknown) => IValidation<T> & StandardSchemaV1<unknown, T>; export function createValidateEquals<T> = (input: unknown) => IValidation<T> & StandardSchemaV1<unknown, T>;

Reusable typia.validate<T>() function generators.

If you repeat to call typia.validate<T>() function on the same type, size of JavaScript files would be larger because of duplicated AOT compilation. To prevent it, you can generate reusable function through typia.createValidate<T>() function.

Just look at the code below, then you may understand how to use it.

examples/src/validators/createValidate.ts
import typia, { tags } from "typia"; export const validateMember = typia.createValidate<IMember>(); interface IMember { id: string & tags.Format<"uuid">; email: string & tags.Format<"email">; age: number & tags.Type<"uint32"> & tags.ExclusiveMinimum<19> & tags.Maximum<100>; }

This reusable function implements Standard Schema  interface. Therefore, you can use this function with a library which accepts Standard Schema interface , such as upfetch :

import typia from "typia"; import { up } from "up-fetch"; const upfetch = up(fetch); const schema = typia.createValidate<ISmallTodo>(); // passes await upfetch("https://jsonplaceholder.typicode.com/todos/1", { schema, }); // fails await upfetch("https://jsonplaceholder.typicode.com/todos/10", { schema, }) interface ISmallTodo { userId: number; /** @maximum 5 */ id: number; title: string; completed: boolean; }

Restrictions

typia.validate<T>() function does not check function and user-defined class types.

It validates only the primitive properties. Therefore, typia.validate<T>() function does not perform the instanceof ClassName for user-defined classes. If you want to validate the user-defined class type in addition to the property types, do it by yourself. Also, typia.validate<T>() function does not validate the function type either, unless configuring functional property of plugin option in the tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "plugins": [ { "transform": "typia/lib/transform", "functional": true } ] } }

By the way, there’re some exception cases.

If JS native class type like Date, Uint8Array, or Map<Key, T> being utilized, typia.validate<T>() function validates them. Especially about the Set<T>, and Map<Key, T> class cases, typia.validate<T>() function validates all of their contained element types, too.

Therefore, the instanceof statement does not be used only for the user-defined classes.

examples/src/validators/validate-map.ts
import typia from "typia"; typia.createIs<Map<string, boolean | number | string>>();

Discriminated Union

@samchon/openapi
/** * Union type representing the result of type validation * * This is the return type of {@link typia.validate} functions, returning * {@link IValidation.ISuccess} on validation success and * {@link IValidation.IFailure} on validation failure. When validation fails, it * provides detailed, granular error information that precisely describes what * went wrong, where it went wrong, and what was expected. * * This comprehensive error reporting makes `IValidation` particularly valuable * for AI function calling scenarios, where Large Language Models (LLMs) need * specific feedback to correct their parameter generation. The detailed error * information is used by ILlmFunction.validate() to provide validation feedback * to AI agents, enabling iterative correction and improvement of function * calling accuracy. * * This type uses the Discriminated Union pattern, allowing type specification * through the success property: * * ```typescript * const result = typia.validate<string>(input); * if (result.success) { * // IValidation.ISuccess<string> type * console.log(result.data); // validated data accessible * } else { * // IValidation.IFailure type * console.log(result.errors); // detailed error information accessible * } * ``` * * @author Jeongho Nam - https://github.com/samchon * @template T The type to validate */ export type IValidation<T = unknown> = | IValidation.ISuccess<T> | IValidation.IFailure; export namespace IValidation { /** * Interface returned when type validation succeeds * * Returned when the input value perfectly conforms to the specified type T. * Since success is true, TypeScript's type guard allows safe access to the * validated data through the data property. * * @template T The validated type */ export interface ISuccess<T = unknown> { /** Indicates validation success */ success: true; /** The validated data of type T */ data: T; } /** * Interface returned when type validation fails * * Returned when the input value does not conform to the expected type. * Contains comprehensive error information designed to be easily understood * by both humans and AI systems. Each error in the errors array provides * precise details about validation failures, including the exact path to the * problematic property, what type was expected, and what value was actually * provided. * * This detailed error structure is specifically optimized for AI function * calling validation feedback. When LLMs make type errors during function * calling, these granular error reports enable the AI to understand exactly * what went wrong and how to fix it, improving success rates in subsequent * attempts. * * Example error scenarios: * * - Type mismatch: expected "string" but got number 5 * - Format violation: expected "string & Format<'uuid'>" but got * "invalid-format" * - Missing properties: expected "required property 'name'" but got undefined * - Array type errors: expected "Array<string>" but got single string value * * The errors are used by ILlmFunction.validate() to provide structured * feedback to AI agents, enabling them to correct their parameter generation * and achieve improved function calling accuracy. */ export interface IFailure { /** Indicates validation failure */ success: false; /** The original input data that failed validation */ data: unknown; /** Array of detailed validation errors */ errors: IError[]; } /** * Detailed information about a specific validation error * * Each error provides granular, actionable information about validation * failures, designed to be immediately useful for both human developers and * AI systems. The error structure follows a consistent format that enables * precise identification and correction of type mismatches. * * This error format is particularly valuable for AI function calling * scenarios, where LLMs need to understand exactly what went wrong to * generate correct parameters. The combination of path, expected type name, * actual value, and optional human-readable description provides the AI with * comprehensive context to make accurate corrections, which is why * ILlmFunction.validate() can achieve such high success rates in validation * feedback loops. * * The value field can contain any type of data, including `undefined` when * dealing with missing required properties or null/undefined validation * scenarios. This allows for precise error reporting in cases where the AI * agent omits required fields or provides null/undefined values * inappropriately. * * Real-world examples from AI function calling: * * { * path: "$input.member.age", * expected: "number", * value: "25" // AI provided string instead of number * } * * { * path: "$input.count", * expected: "number & Type<'uint32'>", * value: 20.75 // AI provided float instead of uint32 * } * * { * path: "$input.categories", * expected: "Array<string>", * value: "technology" // AI provided string instead of array * } * * { * path: "$input.id", * expected: "string & Format<'uuid'>", * value: "invalid-uuid-format" // AI provided malformed UUID * } * * { * path: "$input.user.name", * expected: "string", * value: undefined // AI omitted required property * } */ export interface IError { /** * The path to the property that failed validation * * Dot-notation path using $input prefix indicating the exact location of * the validation failure within the input object structure. Examples * include "$input.member.age", "$input.categories[0]", * "$input.user.profile.email" */ path: string; /** * The expected type name or type expression * * Technical type specification that describes what type was expected at * this path. This follows TypeScript-like syntax with embedded constraint * information, such as "string", "number & Type<'uint32'>", * "Array<string>", "string & Format<'uuid'> & MinLength<8>", etc. */ expected: string; /** * The actual value that caused the validation failure * * This field contains the actual value that was provided but failed * validation. Note that this value can be `undefined` in cases where a * required property is missing or when validating against undefined * values. */ value: unknown; /** * Optional human-readable description of the validation error * * This field is rarely populated in standard typia validation and is * primarily intended for specialized AI agent libraries or custom * validation scenarios that require additional context beyond the technical * type information. Most validation errors rely solely on the path, * expected, and value fields for comprehensive error reporting. */ description?: string; } }

Specify type through if condition.

typia.IValidation<T> is an union type of typia.IValidation.ISuccess<T> and typia.IValidation.IFailure. Also, they have a common property success of boolean type, but different literal values. In that case, if you write a if condition about the success property, you can specify the union type like below.

In TypeScript, such union type specification through common property (of different literal value() is called “Discriminated Union”. Therefore, when using typia.validate<T>() function, let’s utilize such discriminated union specification for convenience.

import typia from "typia"; const something: unknown = ...; const result: typia.IValidation<string> = typia.validate<string>(something); if (results.success) { // become typia.IValidation.Success<string> type result.data; // accessible } else { // become typia.IValidation.Failure type result.errors; //accessible }

Customization

You can enhance validation logic by special tags.

Also, with those tags, you can add your custom validation logic, too.

If you want to know about such special tags detaily, read below article:

examples/src/validators/validate-custom-tags.ts
import typia, { tags } from "typia"; export const validateSomething = typia.createValidate<Something>(); //---- // DEFINE CUSTOM TYPE TAGS //---- type Dollar = tags.TagBase<{ kind: "dollar"; target: "string"; value: undefined; validate: `$input[0] === "$" && !isNaN(Number($input.substring(1).split(",").join("")))`; }>; type Postfix<Value extends string> = tags.TagBase<{ kind: "postfix"; target: "string"; value: Value; validate: `$input.endsWith("${Value}")`; }>; type IsEven<Value extends number | bigint> = tags.TagBase<{ kind: "isEven"; target: Value extends number ? "number" : "bigint"; value: undefined; validate: `$input % ${Numeric<2>} === ${Numeric<0>}`; }>; type Numeric<Value extends number | bigint> = Value extends number ? Value : `BigInt(${Value})`; //---- // VALIDATION //---- interface Something { dollar: string & Dollar; postfix: string & Postfix<"!!!">; isEven: number & IsEven<number>; }

Performance

Super-fast and super-safe.

Comparing typia.validate<T>() function with other competitive libraries, maximum 20,000x faster.

Furthermore, only typia can validate complicate union types.

validate Function Benchmark

Measured on AMD Ryzen 9 7940HS, Rog Flow x13 

ComponentstypiaTypeBoxajvio-tszodC.V.
Easy to use✅❌❌❌❌❌
Object (simple) ✔✔✔✔✔✔
Object (hierarchical) ✔✔✔✔✔✔
Object (recursive) ✔❌✔✔✔✔
Object (union, implicit) ✅❌❌❌❌❌
Object (union, explicit) ✔✔✔✔✔❌
Object (additional tags) ✔✔✔✔✔✔
Object (template literal types) ✔✔✔❌❌❌
Object (dynamic properties) ✔✔✔❌❌❌
Array (rest tuple) ✅❌❌❌❌❌
Array (hierarchical) ✔✔✔✔✔✔
Array (recursive) ✔✔✔✔✔❌
Array (recursive, union) ✔✔❌✔✔❌
Array (R+U, implicit) ✅❌❌❌❌❌
Array (repeated) ✅❌❌❌❌❌
Array (repeated, union) ✅❌❌❌❌❌
Ultimate Union Type✅❌❌❌❌❌

C.V. means class-validator

Last updated on