stringify() functions
undefined
export namespace json {
export function stringify<T>(input: T): string;
export function isStringify<T>(input: T | unknown): string | null;
export function assertStringify<T>(input: T | unknown): string;
export function validateStringify<T>(input: T | unknown): IValidation<string>;
}undefined
/**
* Error thrown when type assertion fails.
*
* Thrown by {@link assert}, {@link assertGuard}, and other assert-family
* functions when input doesn't match expected type `T`. Contains detailed
* information about the first assertion failure:
*
* - `method`: Which typia function threw (e.g., `"typia.assert"`)
* - `path`: Property path where error occurred (e.g., `"input.user.age"`)
* - `expected`: Expected type string (e.g., `"number & ExclusiveMinimum<19>"`)
* - `value`: Actual value that failed validation
*
* @template T Expected type (for type safety)
*/
export class TypeGuardError<T = any> extends Error {
/**
* Name of the typia method that threw this error.
*
* E.g., `"typia.assert"`, `"typia.assertEquals"`, `"typia.assertGuard"`.
*/
public readonly method: string;
/**
* Property path where assertion failed.
*
* Uses dot notation for nested properties. `undefined` if error occurred at
* root level.
*
* E.g., `"input.age"`, `"input.profile.email"`, `"input[0].name"`.
*/
public readonly path: string | undefined;
/**
* String representation of expected type.
*
* E.g., `"string"`, `"number & ExclusiveMinimum<19>"`, `"{ name: string; age:
* number }"`.
*/
public readonly expected: string;
/**
* Actual value that failed assertion.
*
* The raw value at the error path, useful for debugging.
*/
public readonly value: unknown;
/**
* Optional human-readable error description.
*
* Primarily for AI agent libraries or custom validation scenarios needing
* additional context. Standard assertions rely on `path`, `expected`, and
* `value` for error reporting.
*/
public readonly description?: string | undefined;
/**
* Phantom property for TypeScript type safety.
*
* Not used at runtime—exists only to preserve generic type `T` in the type
* system. Always `undefined`.
*
* @internal
*/
protected readonly fake_expected_typed_value_?: T | undefined;
/**
* Creates a new TypeGuardError instance.
*
* @param props Error properties
*/
public constructor(props: TypeGuardError.IProps) {
// MESSAGE CONSTRUCTION
// Use custom message if provided, otherwise generate default format
super(
props.message ||
`Error on ${props.method}(): invalid type${
props.path ? ` on ${props.path}` : ""
}, expect to be ${props.expected}`,
);
// INHERITANCE POLYFILL
// Set up prototype for compatibility across different JavaScript environments
const proto = new.target.prototype;
if (Object.setPrototypeOf) Object.setPrototypeOf(this, proto);
else (this as any).__proto__ = proto;
// ASSIGN MEMBERS
this.method = props.method;
this.path = props.path;
this.expected = props.expected;
this.value = props.value;
if (props.description || props.value === undefined)
this.description =
props.description ??
[
"The value at this path is `undefined`.",
"",
`Please fill the \`${props.expected}\` typed value next time.`,
].join("\n");
}
}
export namespace TypeGuardError {
/** Properties for constructing a TypeGuardError. */
export interface IProps {
/**
* Name of the typia method that threw the error.
*
* E.g., `"typia.assert"`, `"typia.assertEquals"`.
*/
method: string;
/**
* Property path where assertion failed (optional).
*
* E.g., `"input.age"`, `"input.profile.email"`.
*/
path?: undefined | string;
/**
* String representation of expected type.
*
* E.g., `"string"`, `"number & ExclusiveMinimum<19>"`.
*/
expected: string;
/** Actual value that failed assertion. */
value: unknown;
/**
* Optional human-readable error description.
*
* For AI agent libraries or custom validation needing additional context.
*/
description?: string;
/**
* Custom error message (optional).
*
* If not provided, a default message is generated from other properties.
*/
message?: undefined | string;
}
}undefined
/**
* Validation result type with detailed error information.
*
* `IValidation<T>` is the return type of `typia.validate<T>()` and related
* validation functions. Unlike `typia.is<T>()` which returns a boolean, or
* `typia.assert<T>()` which throws exceptions, `typia.validate<T>()` returns
* this structured result with full error details.
*
* Check the {@link IValidation.success | success} discriminator:
*
* - `true` → {@link IValidation.ISuccess} with validated
* {@link IValidation.ISuccess.data | data}
* - `false` → {@link IValidation.IFailure} with
* {@link IValidation.IFailure.errors | errors} array
*
* This is the recommended validation function when you need to report
* validation errors to users or log them for debugging.
*
* @author Jeongho Nam - https://github.com/samchon
* @example
* const result = typia.validate<User>(input);
* if (result.success) {
* return result.data; // User type
* } else {
* result.errors.forEach((e) => console.log(e.path, e.expected));
* }
*
* @template T The expected type after successful validation
*/
export type IValidation<T = unknown> =
| IValidation.ISuccess<T>
| IValidation.IFailure;
export namespace IValidation {
/**
* Successful validation result.
*
* Indicates the input matches the expected type. The validated data is
* available in {@link data} with full type information.
*
* @template T The validated type
*/
export interface ISuccess<T = unknown> {
/**
* Success discriminator.
*
* Always `true` for successful validations. Use this to narrow the type
* before accessing {@link data}.
*/
success: true;
/**
* The validated data with correct type.
*
* The original input after successful validation. TypeScript will narrow
* this to type `T` when {@link success} is `true`.
*/
data: T;
}
/**
* Failed validation result with error details.
*
* Indicates the input did not match the expected type. Contains the original
* data and an array of all validation errors found.
*/
export interface IFailure {
/**
* Success discriminator.
*
* Always `false` for failed validations. Use this to narrow the type before
* accessing {@link errors}.
*/
success: false;
/**
* The original input that failed validation.
*
* Preserved as `unknown` type since it didn't match the expected type.
* Useful for debugging or logging the actual value.
*/
data: unknown;
/**
* Array of validation errors.
*
* Contains one entry for each validation failure found. Multiple errors may
* exist if the input has multiple type mismatches.
*/
errors: IError[];
}
/**
* Detailed information about a single validation error.
*
* Describes exactly what went wrong during validation, including the
* location, expected type, and actual value.
*/
export interface IError {
/**
* Property path to the error location.
*
* A dot-notation path from the root input to the failing property. Uses
* `$input` as the root. Example: `"$input.user.email"` or
* `"$input.items[0].price"`.
*/
path: string;
/**
* Expected type expression.
*
* A human-readable description of what type was expected at this location.
* Examples: `"string"`, `"number & ExclusiveMinimum<0>"`, `"(\"active\" |
* \"inactive\")"`.
*/
expected: string;
/**
* The actual value that failed validation.
*
* The value found at the error path. May be `undefined` if the property was
* missing. Useful for debugging type mismatches.
*/
value: unknown;
/**
* Human-readable error description.
*
* Optional additional context about the validation failure, such as
* constraint violations or custom error messages.
*/
description?: string;
}
}You can boost up JSON serialization speed just by calling typia.json.stringify<T>() function. Also, you even can ensure type safety of JSON serialization by calling other functions like typia.json.isStringify() and typia.json.assertStringify() functions.
As typia.json.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 occurred.
Instead, typia supports type safe JSON serialization functions like typia.json.isStringify(). The typia.json.isStringify() is a combination function of typia.is<T>() and typia.json.stringify<T>() function. It checks whether the input value is valid for the target type T or not first, and operate JSON serialization later. If the input value is not matched with the type T, it returns null value.
typia.json.isStringify():typia.is<T>()+typia.json.stringify<T>()typia.json.assertStringify():typia.assert<T>()+typia.json.stringify<T>()typia.json.validateStringify():typia.validate<T>()+typia.json.stringify<T>()
AOT compilation
typia.json.isStringify() and other similar functions are still much faster than native JSON.stringify() function, even though they include type checking process. This is the power of AOT compilation, writing optimal dedicated code by analyzing TypeScript type, in the compilation level.
TypeScript Source Code
import typia, { tags } from "typia";
const department: IDepartment = typia.random<IDepartment>();
const json: string | null = typia.json.isStringify(department);
console.log(json); // not null, but string
interface IDepartment {
id: string & tags.Format<"uuid">;
name: string & tags.MinLength<3>;
limit: number & tags.Type<"int32">;
clerks: IClerk[];
}
interface IClerk {
name: string;
age: number &
tags.Type<"uint32"> &
tags.ExclusiveMinimum<19> &
tags.Maximum<100>;
authority: number;
joined_at: string & tags.Format<"date">;
}Compiled JavaScript File
import typia from "typia";
import * as __typia_transform__isFormatDate from "typia/lib/internal/_isFormatDate";
import * as __typia_transform__isFormatUuid from "typia/lib/internal/_isFormatUuid";
import * as __typia_transform__isTypeInt32 from "typia/lib/internal/_isTypeInt32";
import * as __typia_transform__isTypeUint32 from "typia/lib/internal/_isTypeUint32";
import * as __typia_transform__jsonStringifyNumber from "typia/lib/internal/_jsonStringifyNumber";
import * as __typia_transform__jsonStringifyString from "typia/lib/internal/_jsonStringifyString";
import * as __typia_transform__randomArray from "typia/lib/internal/_randomArray";
import * as __typia_transform__randomFormatDate from "typia/lib/internal/_randomFormatDate";
import * as __typia_transform__randomFormatUuid from "typia/lib/internal/_randomFormatUuid";
import * as __typia_transform__randomInteger from "typia/lib/internal/_randomInteger";
import * as __typia_transform__randomNumber from "typia/lib/internal/_randomNumber";
import * as __typia_transform__randomString from "typia/lib/internal/_randomString";
const department = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
id: (
_generator?.uuid ?? __typia_transform__randomFormatUuid._randomFormatUuid
)(),
name: (_generator?.string ?? __typia_transform__randomString._randomString)(
{
type: "string",
minLength: 3,
},
),
limit: (
_generator?.integer ?? __typia_transform__randomInteger._randomInteger
)({
type: "integer",
}),
clerks: (_generator?.array ?? __typia_transform__randomArray._randomArray)({
type: "array",
element: () => _ro1(_recursive, _recursive ? 1 + _depth : _depth),
}),
});
const _ro1 = (_recursive = false, _depth = 0) => ({
name: (_generator?.string ?? __typia_transform__randomString._randomString)(
{
type: "string",
},
),
age: (
_generator?.integer ?? __typia_transform__randomInteger._randomInteger
)({
type: "integer",
minimum: 0,
exclusiveMinimum: 19,
maximum: 100,
}),
authority: (
_generator?.number ?? __typia_transform__randomNumber._randomNumber
)({
type: "number",
}),
joined_at: (
_generator?.date ?? __typia_transform__randomFormatDate._randomFormatDate
)(),
});
let _generator;
return (generator) => {
_generator = generator;
return _ro0();
};
})()();
const json = (() => {
const _io0 = (input) =>
"string" === typeof input.id &&
__typia_transform__isFormatUuid._isFormatUuid(input.id) &&
"string" === typeof input.name &&
3 <= input.name.length &&
"number" === typeof input.limit &&
__typia_transform__isTypeInt32._isTypeInt32(input.limit) &&
Array.isArray(input.clerks) &&
input.clerks.every(
(elem) => "object" === typeof elem && null !== elem && _io1(elem),
);
const _io1 = (input) =>
"string" === typeof input.name &&
"number" === typeof input.age &&
__typia_transform__isTypeUint32._isTypeUint32(input.age) &&
19 < input.age &&
input.age <= 100 &&
"number" === typeof input.authority &&
Number.isFinite(input.authority) &&
"string" === typeof input.joined_at &&
__typia_transform__isFormatDate._isFormatDate(input.joined_at);
const _so0 = (input) =>
`{"id":${__typia_transform__jsonStringifyString._jsonStringifyString(input.id)},"name":${__typia_transform__jsonStringifyString._jsonStringifyString(input.name)},"limit":${__typia_transform__jsonStringifyNumber._jsonStringifyNumber(input.limit)},"clerks":${`[${input.clerks.map((elem) => _so1(elem)).join(",")}]`}}`;
const _so1 = (input) =>
`{"name":${__typia_transform__jsonStringifyString._jsonStringifyString(input.name)},"age":${__typia_transform__jsonStringifyNumber._jsonStringifyNumber(input.age)},"authority":${__typia_transform__jsonStringifyNumber._jsonStringifyNumber(input.authority)},"joined_at":${__typia_transform__jsonStringifyString._jsonStringifyString(input.joined_at)}}`;
const __is = (input) =>
"object" === typeof input && null !== input && _io0(input);
const __stringify = (input) => _so0(input);
return (input) => (__is(input) ? __stringify(input) : null);
})()(department);
console.log(json); // not null, but stringReusable functions
undefined
export namespace json {
export function createStringify<T>(): (input: T) => string;
export function createIsStringify<T>(): (input: unknown) => string | null;
export function createAssertStringify<T>(
errorFactory?: undefined | ((props: TypeGuardError.IProps) => Error),
): (input: unknown) => string;
export function createValidateStringify<T>(): (input: unknown) => IValidation<string>;
}undefined
/**
* Error thrown when type assertion fails.
*
* Thrown by {@link assert}, {@link assertGuard}, and other assert-family
* functions when input doesn't match expected type `T`. Contains detailed
* information about the first assertion failure:
*
* - `method`: Which typia function threw (e.g., `"typia.assert"`)
* - `path`: Property path where error occurred (e.g., `"input.user.age"`)
* - `expected`: Expected type string (e.g., `"number & ExclusiveMinimum<19>"`)
* - `value`: Actual value that failed validation
*
* @template T Expected type (for type safety)
*/
export class TypeGuardError<T = any> extends Error {
/**
* Name of the typia method that threw this error.
*
* E.g., `"typia.assert"`, `"typia.assertEquals"`, `"typia.assertGuard"`.
*/
public readonly method: string;
/**
* Property path where assertion failed.
*
* Uses dot notation for nested properties. `undefined` if error occurred at
* root level.
*
* E.g., `"input.age"`, `"input.profile.email"`, `"input[0].name"`.
*/
public readonly path: string | undefined;
/**
* String representation of expected type.
*
* E.g., `"string"`, `"number & ExclusiveMinimum<19>"`, `"{ name: string; age:
* number }"`.
*/
public readonly expected: string;
/**
* Actual value that failed assertion.
*
* The raw value at the error path, useful for debugging.
*/
public readonly value: unknown;
/**
* Optional human-readable error description.
*
* Primarily for AI agent libraries or custom validation scenarios needing
* additional context. Standard assertions rely on `path`, `expected`, and
* `value` for error reporting.
*/
public readonly description?: string | undefined;
/**
* Phantom property for TypeScript type safety.
*
* Not used at runtime—exists only to preserve generic type `T` in the type
* system. Always `undefined`.
*
* @internal
*/
protected readonly fake_expected_typed_value_?: T | undefined;
/**
* Creates a new TypeGuardError instance.
*
* @param props Error properties
*/
public constructor(props: TypeGuardError.IProps) {
// MESSAGE CONSTRUCTION
// Use custom message if provided, otherwise generate default format
super(
props.message ||
`Error on ${props.method}(): invalid type${
props.path ? ` on ${props.path}` : ""
}, expect to be ${props.expected}`,
);
// INHERITANCE POLYFILL
// Set up prototype for compatibility across different JavaScript environments
const proto = new.target.prototype;
if (Object.setPrototypeOf) Object.setPrototypeOf(this, proto);
else (this as any).__proto__ = proto;
// ASSIGN MEMBERS
this.method = props.method;
this.path = props.path;
this.expected = props.expected;
this.value = props.value;
if (props.description || props.value === undefined)
this.description =
props.description ??
[
"The value at this path is `undefined`.",
"",
`Please fill the \`${props.expected}\` typed value next time.`,
].join("\n");
}
}
export namespace TypeGuardError {
/** Properties for constructing a TypeGuardError. */
export interface IProps {
/**
* Name of the typia method that threw the error.
*
* E.g., `"typia.assert"`, `"typia.assertEquals"`.
*/
method: string;
/**
* Property path where assertion failed (optional).
*
* E.g., `"input.age"`, `"input.profile.email"`.
*/
path?: undefined | string;
/**
* String representation of expected type.
*
* E.g., `"string"`, `"number & ExclusiveMinimum<19>"`.
*/
expected: string;
/** Actual value that failed assertion. */
value: unknown;
/**
* Optional human-readable error description.
*
* For AI agent libraries or custom validation needing additional context.
*/
description?: string;
/**
* Custom error message (optional).
*
* If not provided, a default message is generated from other properties.
*/
message?: undefined | string;
}
}undefined
/**
* Validation result type with detailed error information.
*
* `IValidation<T>` is the return type of `typia.validate<T>()` and related
* validation functions. Unlike `typia.is<T>()` which returns a boolean, or
* `typia.assert<T>()` which throws exceptions, `typia.validate<T>()` returns
* this structured result with full error details.
*
* Check the {@link IValidation.success | success} discriminator:
*
* - `true` → {@link IValidation.ISuccess} with validated
* {@link IValidation.ISuccess.data | data}
* - `false` → {@link IValidation.IFailure} with
* {@link IValidation.IFailure.errors | errors} array
*
* This is the recommended validation function when you need to report
* validation errors to users or log them for debugging.
*
* @author Jeongho Nam - https://github.com/samchon
* @example
* const result = typia.validate<User>(input);
* if (result.success) {
* return result.data; // User type
* } else {
* result.errors.forEach((e) => console.log(e.path, e.expected));
* }
*
* @template T The expected type after successful validation
*/
export type IValidation<T = unknown> =
| IValidation.ISuccess<T>
| IValidation.IFailure;
export namespace IValidation {
/**
* Successful validation result.
*
* Indicates the input matches the expected type. The validated data is
* available in {@link data} with full type information.
*
* @template T The validated type
*/
export interface ISuccess<T = unknown> {
/**
* Success discriminator.
*
* Always `true` for successful validations. Use this to narrow the type
* before accessing {@link data}.
*/
success: true;
/**
* The validated data with correct type.
*
* The original input after successful validation. TypeScript will narrow
* this to type `T` when {@link success} is `true`.
*/
data: T;
}
/**
* Failed validation result with error details.
*
* Indicates the input did not match the expected type. Contains the original
* data and an array of all validation errors found.
*/
export interface IFailure {
/**
* Success discriminator.
*
* Always `false` for failed validations. Use this to narrow the type before
* accessing {@link errors}.
*/
success: false;
/**
* The original input that failed validation.
*
* Preserved as `unknown` type since it didn't match the expected type.
* Useful for debugging or logging the actual value.
*/
data: unknown;
/**
* Array of validation errors.
*
* Contains one entry for each validation failure found. Multiple errors may
* exist if the input has multiple type mismatches.
*/
errors: IError[];
}
/**
* Detailed information about a single validation error.
*
* Describes exactly what went wrong during validation, including the
* location, expected type, and actual value.
*/
export interface IError {
/**
* Property path to the error location.
*
* A dot-notation path from the root input to the failing property. Uses
* `$input` as the root. Example: `"$input.user.email"` or
* `"$input.items[0].price"`.
*/
path: string;
/**
* Expected type expression.
*
* A human-readable description of what type was expected at this location.
* Examples: `"string"`, `"number & ExclusiveMinimum<0>"`, `"(\"active\" |
* \"inactive\")"`.
*/
expected: string;
/**
* The actual value that failed validation.
*
* The value found at the error path. May be `undefined` if the property was
* missing. Useful for debugging type mismatches.
*/
value: unknown;
/**
* Human-readable error description.
*
* Optional additional context about the validation failure, such as
* constraint violations or custom error messages.
*/
description?: string;
}
}Reusable typia.json.stringify<T>() function generators.
If you repeat to call typia.json.stringify<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.json.createStringify<T>() function.
Just look at the code below, then you may understand how to use it.
TypeScript Source Code
import typia, { tags } from "typia";
export const assertDepartment = typia.json.createAssertStringify<IDepartment>();
interface IDepartment {
id: string & tags.Format<"uuid">;
name: string & tags.MinLength<3>;
limit: number & tags.Type<"int32">;
clerks: IClerk[];
}
interface IClerk {
name: string;
age: number &
tags.Type<"uint32"> &
tags.ExclusiveMinimum<19> &
tags.Maximum<100>;
authority: number;
joined_at: string & tags.Format<"date">;
}Compiled JavaScript File
import typia from "typia";
import * as __typia_transform__assertGuard from "typia/lib/internal/_assertGuard";
import * as __typia_transform__isFormatDate from "typia/lib/internal/_isFormatDate";
import * as __typia_transform__isFormatUuid from "typia/lib/internal/_isFormatUuid";
import * as __typia_transform__isTypeInt32 from "typia/lib/internal/_isTypeInt32";
import * as __typia_transform__isTypeUint32 from "typia/lib/internal/_isTypeUint32";
import * as __typia_transform__jsonStringifyString from "typia/lib/internal/_jsonStringifyString";
export const assertDepartment = (() => {
const _io0 = (input) =>
"string" === typeof input.id &&
__typia_transform__isFormatUuid._isFormatUuid(input.id) &&
"string" === typeof input.name &&
3 <= input.name.length &&
"number" === typeof input.limit &&
__typia_transform__isTypeInt32._isTypeInt32(input.limit) &&
Array.isArray(input.clerks) &&
input.clerks.every(
(elem) => "object" === typeof elem && null !== elem && _io1(elem),
);
const _io1 = (input) =>
"string" === typeof input.name &&
"number" === typeof input.age &&
__typia_transform__isTypeUint32._isTypeUint32(input.age) &&
19 < input.age &&
input.age <= 100 &&
"number" === typeof input.authority &&
Number.isFinite(input.authority) &&
"string" === typeof input.joined_at &&
__typia_transform__isFormatDate._isFormatDate(input.joined_at);
const _ao0 = (input, _path, _exceptionable = true) =>
(("string" === typeof input.id &&
(__typia_transform__isFormatUuid._isFormatUuid(input.id) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".id",
expected: 'string & Format<"uuid">',
value: input.id,
},
_errorFactory,
))) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".id",
expected: '(string & Format<"uuid">)',
value: input.id,
},
_errorFactory,
)) &&
(("string" === typeof input.name &&
(3 <= input.name.length ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".name",
expected: "string & MinLength<3>",
value: input.name,
},
_errorFactory,
))) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".name",
expected: "(string & MinLength<3>)",
value: input.name,
},
_errorFactory,
)) &&
(("number" === typeof input.limit &&
(__typia_transform__isTypeInt32._isTypeInt32(input.limit) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".limit",
expected: 'number & Type<"int32">',
value: input.limit,
},
_errorFactory,
))) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".limit",
expected: '(number & Type<"int32">)',
value: input.limit,
},
_errorFactory,
)) &&
(((Array.isArray(input.clerks) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".clerks",
expected: "Array<IClerk>",
value: input.clerks,
},
_errorFactory,
)) &&
input.clerks.every(
(elem, _index2) =>
((("object" === typeof elem && null !== elem) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".clerks[" + _index2 + "]",
expected: "IClerk",
value: elem,
},
_errorFactory,
)) &&
_ao1(
elem,
_path + ".clerks[" + _index2 + "]",
true && _exceptionable,
)) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".clerks[" + _index2 + "]",
expected: "IClerk",
value: elem,
},
_errorFactory,
),
)) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".clerks",
expected: "Array<IClerk>",
value: input.clerks,
},
_errorFactory,
));
const _ao1 = (input, _path, _exceptionable = true) =>
("string" === typeof input.name ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".name",
expected: "string",
value: input.name,
},
_errorFactory,
)) &&
(("number" === typeof input.age &&
(__typia_transform__isTypeUint32._isTypeUint32(input.age) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".age",
expected: 'number & Type<"uint32">',
value: input.age,
},
_errorFactory,
)) &&
(19 < input.age ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".age",
expected: "number & ExclusiveMinimum<19>",
value: input.age,
},
_errorFactory,
)) &&
(input.age <= 100 ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".age",
expected: "number & Maximum<100>",
value: input.age,
},
_errorFactory,
))) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".age",
expected:
'(number & Type<"uint32"> & ExclusiveMinimum<19> & Maximum<100>)',
value: input.age,
},
_errorFactory,
)) &&
(("number" === typeof input.authority &&
Number.isFinite(input.authority)) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".authority",
expected: "number",
value: input.authority,
},
_errorFactory,
)) &&
(("string" === typeof input.joined_at &&
(__typia_transform__isFormatDate._isFormatDate(input.joined_at) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".joined_at",
expected: 'string & Format<"date">',
value: input.joined_at,
},
_errorFactory,
))) ||
__typia_transform__assertGuard._assertGuard(
_exceptionable,
{
method: "typia.json.createAssertStringify",
path: _path + ".joined_at",
expected: '(string & Format<"date">)',
value: input.joined_at,
},
_errorFactory,
));
const _so0 = (input) =>
`{"id":${__typia_transform__jsonStringifyString._jsonStringifyString(input.id)},"name":${__typia_transform__jsonStringifyString._jsonStringifyString(input.name)},"limit":${input.limit},"clerks":${`[${input.clerks.map((elem) => _so1(elem)).join(",")}]`}}`;
const _so1 = (input) =>
`{"name":${__typia_transform__jsonStringifyString._jsonStringifyString(input.name)},"age":${input.age},"authority":${input.authority},"joined_at":${__typia_transform__jsonStringifyString._jsonStringifyString(input.joined_at)}}`;
const __is = (input) =>
"object" === typeof input && null !== input && _io0(input);
let _errorFactory;
const __assert = (input, errorFactory) => {
if (false === __is(input)) {
_errorFactory = errorFactory;
((input, _path, _exceptionable = true) =>
((("object" === typeof input && null !== input) ||
__typia_transform__assertGuard._assertGuard(
true,
{
method: "typia.json.createAssertStringify",
path: _path + "",
expected: "IDepartment",
value: input,
},
_errorFactory,
)) &&
_ao0(input, _path + "", true)) ||
__typia_transform__assertGuard._assertGuard(
true,
{
method: "typia.json.createAssertStringify",
path: _path + "",
expected: "IDepartment",
value: input,
},
_errorFactory,
))(input, "$input", true);
}
return input;
};
const __stringify = (input) => _so0(input);
return (input, errorFactory) => {
__assert(input, errorFactory);
return __stringify(input);
};
})();Performance
Comparing JSON serialization speed with others, it is maximum 200x faster than class-transformer.
For reference, class-transformer is the most famous library used in NestJS with class-validator. Also, fast-json-stringify is another famous one used in fastify. However, whether they are fast or slow, both of them require extra schema definition, that is different with TypeScript type. If you see the code below without experience of them, you may get shocked: how complicate and inefficient they are:
fast-json-stringifyrequires JSON schema definition .class-validatorrequires DTO class with decorator function calls .
Measured on AMD Ryzen 9 7940HS, Rog Flow x13
Server Performance
Someone may ask:
JSON serialization speed affects on the server performance?
I think that the JSON serialization is just a tiny thing in the server side, isn’t it?
My answer is, “Yes, it affects on the server performance”.
Most operations in NodeJS server are asynchronously executed in background thread, what are called “event based non-blocking I/O model”. However, JSON serialization is a synchronous operation running on the main thread. Therefore, if the JSON serialization speed is slow, it makes the entire server program slow.
I’ll show you the benchmark result that, how JSON serizliation speed affects on the server performance.
Measured on AMD Ryzen 9 7940HS, Rog Flow x13