iTranslated by AI
Using Typia: A Validation Library 1500x Faster Than Zod
Introduction
There are several libraries for TypeScript validation, but Zod seems to be one of the most popular ones lately.
I often use Zod myself, but I recently discovered a library called Typia and gave it a try. Typia's key features are its easy-to-understand syntax and its speed. Let's take a look at it while comparing it with Zod.
Comparison of Syntax
Setting aside installation and detailed usage for a moment, let's first compare the validation syntax of Zod and Typia.
// Zod
import { z } from "zod";
const User = z.object({
username: z.string(),
});
User.parse({ username: "Ludwig" });
// You can also extract the inferred type
type IUser = z.infer<typeof User>;
// { username: string }
// Typia
import typia from "typia";
interface IUser {
username: string;
}
typia.assert<IUser>({ username: "Ludwig" });
Zod creates a Zod object and uses it for validation. On the other hand, Typia uses the interface directly for validation. While Zod allows you to extract types using z.infer(), Typia does not require this step.
Validation Options
In Zod, you can perform validations such as email addresses or UUIDs using validator.js. Typia uses comment tags to perform these validations.
// Zod
z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().email();
z.string().url();
z.string().emoji();
z.string().uuid();
z.string().cuid();
z.string().cuid2();
z.string().ulid();
z.string().regex(regex);
z.string().includes(string);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().datetime(); // defaults to UTC, see below for options
z.string().ip(); // defaults to IPv4 and IPv6, see below for options
// Typia
export const checkCommentTag = typia.createIs<CommentTag>();
interface CommentTag {
/**
* @type int
*/
type: number;
/**
* @exclusiveMinimum 19
* @maximum 100
*/
number?: number;
/**
* @minLength 3
*/
string: string;
/**
* @pattern ^[a-z]+$
*/
pattern: string;
/**
* @format date-time
*/
format: string | null;
/**
* In the Array case, possible to restrict its elements.
*
* @minItems 3
* @maxItems 100
* @format uuid
*/
array: string[];
}
Zod uses validator.js, offering a wide variety of options. Typia supports fewer tags, but includes the following set. The bare necessities are implemented, and you are encouraged to create custom tags if needed. (Customization)
- number
@type {"int"|"uint"}@minimum {number}@maximum {number}@exclusiveMinimum {number}@exclusiveMaximum {number}@multipleOf {number}
- string
@minLength {number}@maxLength {number}@pattern {regex}-
@format {keyword}emailuuidipv4ipv6date: YYYY-MM-DDdate-time: Date.toISOString()
- array
@minItems {number}@maxItems {number}
Validation Methods
Just as Zod has safeParse(), Typia provides methods like is(), assert(), and validate(), which you can choose depending on whether you want to throw an error or not.
// Zod
User.safeParse({ username: "Ludwig" });
// Typia
const matched: boolean = typia.is<IUser>({
username: "Ludwig",
});
console.log(matched); // true
const res: typia.IValidation<IUser> = typia.validate<IUser>({
username: 5,
});
if (!res.success) console.log(res.errors);
Parsing JSON Strings
Typia also provides methods like parse() for parsing JSON strings, allowing you to validate data without needing an intermediate JSON.parse() call.
// Zod
User.parse(JSON.parse("{ username: \"Ludwig\" }"));
// Typia
const parsed: IUser = typia.assertParse<IUser>("{ username: \"Ludwig\" }");
Typia also provides stringify(). I thought JSON.stringify() would be sufficient, but it appears to perform faster than the native stringify. (stringify() functions)
As typia.stringify<T>() function writes dedicated JSON serialization code only for the target type T, its performance is much faster than native JSON.stringify() function. However, because of the dedicated optimal JSON serialization code, when wrong typed data comes, unexpected error be occured.
Value Transformation
While Zod has a transform() method to convert validated values into different ones, Typia does not provide such functionality.
Speed Comparison
Typia claims to be "Super-fast and super-safe," and they have published their benchmarks, including source code, against other libraries. I ran the benchmarks locally using their provided code. I used safeParse() for Zod and the is() method for Typia.

Surprisingly, in the simple object case, Typia scores over 1,500 times faster than Zod. Furthermore, Typia is capable of validating complex union types.
I also measured the benchmark for stringify compared to the native implementation. Indeed, for a simple object, Typia appears to run about six times faster.

Introducing Typia
Now that I've explained the comparison with Zod, let's look at how to introduce Typia. There are two modes for using Typia.
Typia offers Transformation mode and Generation mode. Transformation mode can be used when compiling TypeScript with tsc, while Generation mode is used when compiling via other methods such as swc.
Transformation Mode
Transformation mode is an AOT (Ahead of Time) compilation mode that allows you to create validations most easily. You can introduce Typia by executing the following commands. Running npx typia setup automatically handles the installation of necessary libraries and the configuration of npm scripts.
% yarn add typia
% npx typia setup
----------------------------------------
Typia Setup Wizard
----------------------------------------
? Package Manager yarn // Select the package manager you are using
yarn add -D ts-patch@latest
yarn add -D ts-node@latest
yarn add -D typescript@4.9.5
npm run prepare
When you compile the file below with the tsc command, optimized validation code for the IMember type is written into the output JavaScript file.
import typia from "typia";
export const check = typia.createIs<IMember>();
interface IMember {
/**
* @format uuid
*/
id: string;
/**
* @format email
*/
email: string;
/**
* @exclusiveMinimum 19
* @maximum 100
*/
age: number;
}
import typia from "typia";
export const check = (input) => {
const $is_uuid = typia.createIs.is_uuid;
const $is_email = typia.createIs.is_email;
return "object" === typeof input &&
null !== input &&
(
"string" === typeof input.id && $is_uuid(input.id) &&
("string" === typeof input.email && $is_email(input.email)) &&
("number" === typeof input.age && 19 < input.age && 100 >= input.age)
);
};
In the example above, createIs<T>() is used. This is a function generator for the reusable is<T>() function. Calling the is<T>() function repeatedly for the same type would cause duplicate AOT compilation, increasing the JavaScript file size, but using the createIs<T>() function avoids this issue.
Update (2023/12/28)
I have confirmed that it also works with Vite by configuring vite.config.ts as follows:
import { defineConfig } from 'vite';
import typescript from 'rollup-plugin-typescript2';
import tspCompiler from 'ts-patch/compiler';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
{
...typescript({
typescript: tspCompiler,
}),
enforce: 'post',
},
],
esbuild: false,
});
Generation Mode
If you are using a non-standard TypeScript compiler like swc, Transformation mode cannot be used, so you must use Generation mode.
Generation mode is slightly cumbersome because you must execute the generate command, which reads the TypeScript code from --input and writes the transformed TypeScript code to the --output directory.
npm install --save typia
# GENERATE TRANSFORMED TYPESCRIPT CODES
npx typia generate \
--input src/templates \
--output src/generated \
--project tsconfig.json
import typia from "typia";
import { IMember } from "../structures/IMember";
export const check = typia.createIs<IMember>();
import typia from "typia";
import { IMember } from "../structures/IMember";
export const check = (input: any): input is IMember => {
const $is_uuid = (typia.createIs as any).is_uuid;
const $is_email = (typia.createIs as any).is_email;
return "object" === typeof input &&
null !== input &&
(
"string" === typeof input.id && is_uuid(input.id) &&
("string" === typeof input.email && $is_email(input.email)) &&
("number" === typeof input.age && 19 <= input.age && 100 >= input.age)
);
};
In practice, you need to execute this before npm run dev or npm run build. Also, when using validation, you will need to import and use the generated files.
// Import from the generated TypeScript file
import {check} from "../generated/check";
console.log(
check({
id: 'aa1ff915-3907-d321-d724-cf5b2eb3057d',
email: 'test@example.com',
age: 20,
})
);
As far as I have confirmed, you cannot use wildcards when specifying files for --input and --output, so at present, you have to write your validations in one location and output the generated files to another. This is one aspect I found inconvenient.
Other Usage
Typia provides a set of helper libraries called Nestia for NestJS, which supports the following features. As verified in the speed comparison, it runs more than 10,000 times faster than class-validator.
Nestia is a set of helper libraries for NestJS, supporting below features:
- @nestia/core: superfast decorators using typia
- @nestia/sdk: evolved SDK and Swagger generators
- @nestia/migrate: Swagger to NestJS
- nestia: just CLI (command line interface) tool
Additionally, examples of usage with Prisma and tRPC are also available.
Summary
I often use Next.js, which forces me to use Generation mode. My concern there is that I have to think about things like which directory to place the validation files in.
However, the speed and the fact that you only need to provide an interface instead of creating custom validation library objects are very appealing. I also think it could be very powerful in server-side applications like NestJS.
References
- https://typia.io/docs/
- https://nestia.io/docs/
- https://github.com/colinhacks/zod
- https://dev.to/samchon/typescript-json-is-10-1000x-times-faster-than-zod-and-io-ts-8n6
- https://dev.to/samchon/i-made-10x-faster-jsonstringify-functions-even-type-safe-2eme
- https://dev.to/samchon/typia-15000x-faster-validator-and-its-histories-1fmg
- https://dev.to/samchon/i-made-express-faster-than-fastify-4h8g
Discussion