random()
function
undefined
export function random<T>(g?: IRandomGenerator): Resolved<T>;
undefined
import { OpenApi } from "@samchon/openapi";
/**
* Interface for generating random values for various data types.
*
* `IRandomGenerator` defines the contract for generating random values that can
* be used by typia for creating mock data, testing scenarios, and random value
* generation based on JSON schema constraints.
*
* This interface supports generating random values for:
*
* - Basic types (boolean, number, integer, bigint, string, array)
* - String format patterns (email, URL, UUID, etc.)
* - Date and time formats
* - Various address and identifier formats
*
* @author Jeongho Nam - https://github.com/samchon
* @example
* ```typescript
* const generator: IRandomGenerator = {
* boolean: () => Math.random() > 0.5,
* number: (schema) => Math.random() * (schema.maximum ?? 100),
* string: (schema) => "example-string",
* email: () => "test@example.com",
* // ... implement other methods
* };
* ```;
*/
export interface IRandomGenerator {
// REGULAR DATA TYPES
/**
* Generates a random boolean value.
*
* @returns Random boolean value or undefined
*/
boolean(): boolean | undefined;
/**
* Generates a random number based on JSON schema constraints.
*
* @param schema JSON schema with number constraints (min, max, etc.)
* @returns Random number within the specified constraints
*/
number(schema: OpenApi.IJsonSchema.INumber): number;
/**
* Generates a random integer based on JSON schema constraints.
*
* @param schema JSON schema with integer constraints (min, max, etc.)
* @returns Random integer within the specified constraints
*/
integer(schema: OpenApi.IJsonSchema.IInteger): number;
/**
* Generates a random bigint based on JSON schema constraints.
*
* @param schema JSON schema with integer constraints (min, max, etc.)
* @returns Random bigint within the specified constraints
*/
bigint(schema: OpenApi.IJsonSchema.IInteger): bigint;
/**
* Generates a random string based on JSON schema constraints.
*
* @param schema JSON schema with string constraints (minLength, maxLength,
* pattern, etc.)
* @returns Random string matching the specified constraints
*/
string(schema: OpenApi.IJsonSchema.IString): string;
/**
* Generates a random array with elements created by the provided generator
* function.
*
* @param schema Array schema with element generator function
* @returns Random array with generated elements
*/
array<T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
element: (index: number, count: number) => T;
},
): T[];
/**
* Generates a random string matching the given regular expression pattern.
*
* @param regex Regular expression pattern to match
* @returns Random string matching the pattern
*/
pattern(regex: RegExp): string;
//----
// STRING FORMATS
//----
// SPECIAL CHARACTER FORMATS
/**
* Generates a random base64-encoded byte string.
*
* @returns Random base64 string
*/
byte(): string;
/**
* Generates a random password string.
*
* @returns Random password
*/
password(): string;
/**
* Generates a random regular expression pattern string.
*
* @returns Random regex pattern
*/
regex(): string;
/**
* Generates a random UUID (Universally Unique Identifier).
*
* @returns Random UUID string in standard format
*/
uuid(): string;
// ADDRESS AND IDENTIFIER FORMATS
/**
* Generates a random email address.
*
* @returns Random email address
*/
email(): string;
/**
* Generates a random hostname.
*
* @returns Random hostname
*/
hostname(): string;
/**
* Generates a random internationalized email address.
*
* @returns Random IDN email address
*/
idnEmail(): string;
/**
* Generates a random internationalized hostname.
*
* @returns Random IDN hostname
*/
idnHostname(): string;
/**
* Generates a random IRI (Internationalized Resource Identifier).
*
* @returns Random IRI
*/
iri(): string;
/**
* Generates a random IRI reference.
*
* @returns Random IRI reference
*/
iriReference(): string;
/**
* Generates a random IPv4 address.
*
* @returns Random IPv4 address
*/
ipv4(): string;
/**
* Generates a random IPv6 address.
*
* @returns Random IPv6 address
*/
ipv6(): string;
/**
* Generates a random URI (Uniform Resource Identifier).
*
* @returns Random URI
*/
uri(): string;
/**
* Generates a random URI reference.
*
* @returns Random URI reference
*/
uriReference(): string;
/**
* Generates a random URI template.
*
* @returns Random URI template
*/
uriTemplate(): string;
/**
* Generates a random URL (Uniform Resource Locator).
*
* @returns Random URL
*/
url(): string;
// DATE AND TIME FORMATS
/**
* Generates a random datetime string in ISO 8601 format.
*
* @param props Optional constraints for minimum and maximum timestamp values
* @returns Random datetime string
*/
datetime(props?: { minimum?: number; maximum?: number }): string;
/**
* Generates a random date string in ISO 8601 format (YYYY-MM-DD).
*
* @param props Optional constraints for minimum and maximum timestamp values
* @returns Random date string
*/
date(props?: { minimum?: number; maximum?: number }): string;
/**
* Generates a random time string in ISO 8601 format (HH:MM:SS).
*
* @returns Random time string
*/
time(): string;
/**
* Generates a random duration string in ISO 8601 format.
*
* @returns Random duration string
*/
duration(): string;
// JSON POINTER FORMATS
/**
* Generates a random JSON pointer string.
*
* @returns Random JSON pointer
*/
jsonPointer(): string;
/**
* Generates a random relative JSON pointer string.
*
* @returns Random relative JSON pointer
*/
relativeJsonPointer(): string;
}
export namespace IRandomGenerator {
/**
* Map of custom generators for different data types.
*
* This interface allows customization of random generation for specific types
* when they have certain schema properties or constraints.
*
* @example
* ```typescript
* const generator: Partial<IRandomGenerator> = {
* string: (schema) => {
* if ((schema as any)["x-typia-monetary"] === "dollar") {
* return "$" + Math.floor(Math.random() * 1000);
* }
* return "default-string";
* },
* number: (schema) => {
* if ((schema as any)["x-typia-powerOf"] !== undefined) {
* const powerOf = (schema as any)["x-typia-powerOf"];
* return Math.pow(powerOf, Math.random() * 10 + 1);
* }
* return Math.random() * 100;
* }
* };
* ```;
*/
export interface CustomMap {
/**
* Custom string generator that can handle special string formats based on
* schema properties.
*/
string?: (
schema: OpenApi.IJsonSchema.IString & Record<string, any>,
) => string;
/**
* Custom number generator that can handle special number constraints based
* on schema properties.
*/
number?: (
schema: OpenApi.IJsonSchema.INumber & Record<string, any>,
) => number;
/**
* Custom integer generator that can handle special integer constraints
* based on schema properties.
*/
integer?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => number;
/**
* Custom bigint generator that can handle special bigint constraints based
* on schema properties.
*/
bigint?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => bigint;
/**
* Custom boolean generator that can handle special boolean constraints
* based on schema properties.
*/
boolean?: (schema: Record<string, any>) => boolean | undefined;
/**
* Custom array generator that can handle special array constraints based on
* schema properties.
*/
array?: <T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
element: (index: number, count: number) => T;
} & Record<string, any>,
) => T[];
}
}
undefined
export type Customizable = {
number: number;
string: string;
bigint: bigint;
};
undefined
import { Equal } from "./typings/Equal";
import { IsTuple } from "./typings/IsTuple";
import { NativeClass } from "./typings/NativeClass";
import { ValueOf } from "./typings/ValueOf";
/**
* Resolved type that erases every method.
*
* `Resolved` is a TMP (Type Meta Programming) type which converts its argument
* as a resolved type that erases every method property.
*
* If the target argument is a built-in class which returns its origin primitive
* type through the `valueOf()` method like the `String` or `Number`, its return
* type will be the `string` or `number`. Otherwise, if the built-in class does
* not have the `valueOf()` method, the return type will be the same as the
* target argument.
*
* Otherwise, if the target argument is a type of custom class, all of its
* custom methods will be erased and its prototype will be changed to the
* primitive `object`. Therefore, the return type of the TMP type will finally
* be the resolved object.
*
* Before | After
* ------------------------|---------------------------------------- `Boolean` |
* `boolean` `Number` | `number` `BigInt` | `bigint` `String` | `string` `Class`
* | `interface` Native Class or Others | No change
*
* @author Jeongho Nam - https://github.com/samchon
* @author Kyungsu Kang - https://github.com/kakasoo
* @template T Target argument type.
*/
export type Resolved<T> =
Equal<T, ResolvedMain<T>> extends true ? T : ResolvedMain<T>;
type ResolvedMain<T> = T extends [never]
? never // (special trick for jsonable | null) type
: ValueOf<T> extends boolean | number | bigint | string
? ValueOf<T>
: T extends Function
? never
: T extends object
? ResolvedObject<T>
: ValueOf<T>;
type ResolvedObject<T extends object> =
T extends Array<infer U>
? IsTuple<T> extends true
? ResolvedTuple<T>
: ResolvedMain<U>[]
: T extends Set<infer U>
? Set<ResolvedMain<U>>
: T extends Map<infer K, infer V>
? Map<ResolvedMain<K>, ResolvedMain<V>>
: T extends WeakSet<any> | WeakMap<any, any>
? never
: T extends NativeClass
? T
: {
[P in keyof T]: ResolvedMain<T[P]>;
};
type ResolvedTuple<T extends readonly any[]> = T extends []
? []
: T extends [infer F]
? [ResolvedMain<F>]
: T extends [infer F, ...infer Rest extends readonly any[]]
? [ResolvedMain<F>, ...ResolvedTuple<Rest>]
: T extends [(infer F)?]
? [ResolvedMain<F>?]
: T extends [(infer F)?, ...infer Rest extends readonly any[]]
? [ResolvedMain<F>?, ...ResolvedTuple<Rest>]
: [];
You can make every random data just by calling typia.random<T>()
function.
When you call the typia.random<T>()
function, typia
will analyze your type T
, and writes optimal random generation code for the type T
, in the compilation level. This is called AOT (Ahead of Time) compilation, and you may understand what it is just by reading below example code.
TypeScript Source Code
import typia, { tags } from "typia";
const member: IMember = typia.random<IMember>();
console.log(member);
interface IMember {
id: string & tags.Format<"uuid">;
email: string & tags.Format<"email">;
age: number &
tags.Type<"uint32"> &
tags.ExclusiveMinimum<19> &
tags.Maximum<100>;
}
Compiled JavaScript File
import typia from "typia";
import * as __typia_transform__randomFormatEmail from "typia/lib/internal/_randomFormatEmail.js";
import * as __typia_transform__randomFormatUuid from "typia/lib/internal/_randomFormatUuid.js";
import * as __typia_transform__randomInteger from "typia/lib/internal/_randomInteger.js";
const member = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
id: (
_generator?.uuid ?? __typia_transform__randomFormatUuid._randomFormatUuid
)(),
email: (
_generator?.email ??
__typia_transform__randomFormatEmail._randomFormatEmail
)(),
age: (
_generator?.integer ?? __typia_transform__randomInteger._randomInteger
)({
type: "integer",
minimum: 0,
exclusiveMinimum: 19,
maximum: 100,
}),
});
let _generator;
return (generator) => {
_generator = generator;
return _ro0();
};
})()();
console.log(member);
Reusable function
undefined
export function createRandom<T>(): (g?: IRandomGenerator) => Resolved<T>;
undefined
import { OpenApi } from "@samchon/openapi";
/**
* Interface for generating random values for various data types.
*
* `IRandomGenerator` defines the contract for generating random values that can
* be used by typia for creating mock data, testing scenarios, and random value
* generation based on JSON schema constraints.
*
* This interface supports generating random values for:
*
* - Basic types (boolean, number, integer, bigint, string, array)
* - String format patterns (email, URL, UUID, etc.)
* - Date and time formats
* - Various address and identifier formats
*
* @author Jeongho Nam - https://github.com/samchon
* @example
* ```typescript
* const generator: IRandomGenerator = {
* boolean: () => Math.random() > 0.5,
* number: (schema) => Math.random() * (schema.maximum ?? 100),
* string: (schema) => "example-string",
* email: () => "test@example.com",
* // ... implement other methods
* };
* ```;
*/
export interface IRandomGenerator {
// REGULAR DATA TYPES
/**
* Generates a random boolean value.
*
* @returns Random boolean value or undefined
*/
boolean(): boolean | undefined;
/**
* Generates a random number based on JSON schema constraints.
*
* @param schema JSON schema with number constraints (min, max, etc.)
* @returns Random number within the specified constraints
*/
number(schema: OpenApi.IJsonSchema.INumber): number;
/**
* Generates a random integer based on JSON schema constraints.
*
* @param schema JSON schema with integer constraints (min, max, etc.)
* @returns Random integer within the specified constraints
*/
integer(schema: OpenApi.IJsonSchema.IInteger): number;
/**
* Generates a random bigint based on JSON schema constraints.
*
* @param schema JSON schema with integer constraints (min, max, etc.)
* @returns Random bigint within the specified constraints
*/
bigint(schema: OpenApi.IJsonSchema.IInteger): bigint;
/**
* Generates a random string based on JSON schema constraints.
*
* @param schema JSON schema with string constraints (minLength, maxLength,
* pattern, etc.)
* @returns Random string matching the specified constraints
*/
string(schema: OpenApi.IJsonSchema.IString): string;
/**
* Generates a random array with elements created by the provided generator
* function.
*
* @param schema Array schema with element generator function
* @returns Random array with generated elements
*/
array<T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
element: (index: number, count: number) => T;
},
): T[];
/**
* Generates a random string matching the given regular expression pattern.
*
* @param regex Regular expression pattern to match
* @returns Random string matching the pattern
*/
pattern(regex: RegExp): string;
//----
// STRING FORMATS
//----
// SPECIAL CHARACTER FORMATS
/**
* Generates a random base64-encoded byte string.
*
* @returns Random base64 string
*/
byte(): string;
/**
* Generates a random password string.
*
* @returns Random password
*/
password(): string;
/**
* Generates a random regular expression pattern string.
*
* @returns Random regex pattern
*/
regex(): string;
/**
* Generates a random UUID (Universally Unique Identifier).
*
* @returns Random UUID string in standard format
*/
uuid(): string;
// ADDRESS AND IDENTIFIER FORMATS
/**
* Generates a random email address.
*
* @returns Random email address
*/
email(): string;
/**
* Generates a random hostname.
*
* @returns Random hostname
*/
hostname(): string;
/**
* Generates a random internationalized email address.
*
* @returns Random IDN email address
*/
idnEmail(): string;
/**
* Generates a random internationalized hostname.
*
* @returns Random IDN hostname
*/
idnHostname(): string;
/**
* Generates a random IRI (Internationalized Resource Identifier).
*
* @returns Random IRI
*/
iri(): string;
/**
* Generates a random IRI reference.
*
* @returns Random IRI reference
*/
iriReference(): string;
/**
* Generates a random IPv4 address.
*
* @returns Random IPv4 address
*/
ipv4(): string;
/**
* Generates a random IPv6 address.
*
* @returns Random IPv6 address
*/
ipv6(): string;
/**
* Generates a random URI (Uniform Resource Identifier).
*
* @returns Random URI
*/
uri(): string;
/**
* Generates a random URI reference.
*
* @returns Random URI reference
*/
uriReference(): string;
/**
* Generates a random URI template.
*
* @returns Random URI template
*/
uriTemplate(): string;
/**
* Generates a random URL (Uniform Resource Locator).
*
* @returns Random URL
*/
url(): string;
// DATE AND TIME FORMATS
/**
* Generates a random datetime string in ISO 8601 format.
*
* @param props Optional constraints for minimum and maximum timestamp values
* @returns Random datetime string
*/
datetime(props?: { minimum?: number; maximum?: number }): string;
/**
* Generates a random date string in ISO 8601 format (YYYY-MM-DD).
*
* @param props Optional constraints for minimum and maximum timestamp values
* @returns Random date string
*/
date(props?: { minimum?: number; maximum?: number }): string;
/**
* Generates a random time string in ISO 8601 format (HH:MM:SS).
*
* @returns Random time string
*/
time(): string;
/**
* Generates a random duration string in ISO 8601 format.
*
* @returns Random duration string
*/
duration(): string;
// JSON POINTER FORMATS
/**
* Generates a random JSON pointer string.
*
* @returns Random JSON pointer
*/
jsonPointer(): string;
/**
* Generates a random relative JSON pointer string.
*
* @returns Random relative JSON pointer
*/
relativeJsonPointer(): string;
}
export namespace IRandomGenerator {
/**
* Map of custom generators for different data types.
*
* This interface allows customization of random generation for specific types
* when they have certain schema properties or constraints.
*
* @example
* ```typescript
* const generator: Partial<IRandomGenerator> = {
* string: (schema) => {
* if ((schema as any)["x-typia-monetary"] === "dollar") {
* return "$" + Math.floor(Math.random() * 1000);
* }
* return "default-string";
* },
* number: (schema) => {
* if ((schema as any)["x-typia-powerOf"] !== undefined) {
* const powerOf = (schema as any)["x-typia-powerOf"];
* return Math.pow(powerOf, Math.random() * 10 + 1);
* }
* return Math.random() * 100;
* }
* };
* ```;
*/
export interface CustomMap {
/**
* Custom string generator that can handle special string formats based on
* schema properties.
*/
string?: (
schema: OpenApi.IJsonSchema.IString & Record<string, any>,
) => string;
/**
* Custom number generator that can handle special number constraints based
* on schema properties.
*/
number?: (
schema: OpenApi.IJsonSchema.INumber & Record<string, any>,
) => number;
/**
* Custom integer generator that can handle special integer constraints
* based on schema properties.
*/
integer?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => number;
/**
* Custom bigint generator that can handle special bigint constraints based
* on schema properties.
*/
bigint?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => bigint;
/**
* Custom boolean generator that can handle special boolean constraints
* based on schema properties.
*/
boolean?: (schema: Record<string, any>) => boolean | undefined;
/**
* Custom array generator that can handle special array constraints based on
* schema properties.
*/
array?: <T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
element: (index: number, count: number) => T;
} & Record<string, any>,
) => T[];
}
}
undefined
export type Customizable = {
number: number;
string: string;
bigint: bigint;
};
undefined
import { Equal } from "./typings/Equal";
import { IsTuple } from "./typings/IsTuple";
import { NativeClass } from "./typings/NativeClass";
import { ValueOf } from "./typings/ValueOf";
/**
* Resolved type that erases every method.
*
* `Resolved` is a TMP (Type Meta Programming) type which converts its argument
* as a resolved type that erases every method property.
*
* If the target argument is a built-in class which returns its origin primitive
* type through the `valueOf()` method like the `String` or `Number`, its return
* type will be the `string` or `number`. Otherwise, if the built-in class does
* not have the `valueOf()` method, the return type will be the same as the
* target argument.
*
* Otherwise, if the target argument is a type of custom class, all of its
* custom methods will be erased and its prototype will be changed to the
* primitive `object`. Therefore, the return type of the TMP type will finally
* be the resolved object.
*
* Before | After
* ------------------------|---------------------------------------- `Boolean` |
* `boolean` `Number` | `number` `BigInt` | `bigint` `String` | `string` `Class`
* | `interface` Native Class or Others | No change
*
* @author Jeongho Nam - https://github.com/samchon
* @author Kyungsu Kang - https://github.com/kakasoo
* @template T Target argument type.
*/
export type Resolved<T> =
Equal<T, ResolvedMain<T>> extends true ? T : ResolvedMain<T>;
type ResolvedMain<T> = T extends [never]
? never // (special trick for jsonable | null) type
: ValueOf<T> extends boolean | number | bigint | string
? ValueOf<T>
: T extends Function
? never
: T extends object
? ResolvedObject<T>
: ValueOf<T>;
type ResolvedObject<T extends object> =
T extends Array<infer U>
? IsTuple<T> extends true
? ResolvedTuple<T>
: ResolvedMain<U>[]
: T extends Set<infer U>
? Set<ResolvedMain<U>>
: T extends Map<infer K, infer V>
? Map<ResolvedMain<K>, ResolvedMain<V>>
: T extends WeakSet<any> | WeakMap<any, any>
? never
: T extends NativeClass
? T
: {
[P in keyof T]: ResolvedMain<T[P]>;
};
type ResolvedTuple<T extends readonly any[]> = T extends []
? []
: T extends [infer F]
? [ResolvedMain<F>]
: T extends [infer F, ...infer Rest extends readonly any[]]
? [ResolvedMain<F>, ...ResolvedTuple<Rest>]
: T extends [(infer F)?]
? [ResolvedMain<F>?]
: T extends [(infer F)?, ...infer Rest extends readonly any[]]
? [ResolvedMain<F>?, ...ResolvedTuple<Rest>]
: [];
Special Tags
Runtime validators of typia
provides additional type checking logic through Type Tags and Comment Tags. typia.random<T>()
function also like that. typia.random<T>()
function can utilize those tags to specialize the behavior of random data generation.
For reference, whether you choose Type Tags or Comment Tags. typia.random<T>()
, it is not a matter for typia.random<T>()
function. Below two TypeScript codes are generating exactly same JavaScript code. Therefore, you can choose whatever you want considering your preference.
TypeScript (Type Tags)
import typia, { tags } from "typia";
const data: TypeTag = typia.random<TypeTag>();
console.log(data);
interface TypeTag {
type: number & tags.Type<"int32">;
number?: number & tags.ExclusiveMinimum<19> & tags.Maximum<100>;
string: string & tags.MinLength<3>;
pattern: string & tags.Pattern<"^[a-z]+$">;
format: (string & tags.Format<"date-time">) | null;
}
TypeScript (Comment Tags)
import typia from "typia";
const data: TypeTag = typia.random<TypeTag>();
console.log(data);
interface TypeTag {
/**
* @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;
}
Compiled JavaScript File
import typia from "typia";
import * as __typia_transform__randomFormatDatetime from "typia/lib/internal/_randomFormatDatetime.js";
import * as __typia_transform__randomInteger from "typia/lib/internal/_randomInteger.js";
import * as __typia_transform__randomNumber from "typia/lib/internal/_randomNumber.js";
import * as __typia_transform__randomPattern from "typia/lib/internal/_randomPattern.js";
import * as __typia_transform__randomPick from "typia/lib/internal/_randomPick.js";
import * as __typia_transform__randomString from "typia/lib/internal/_randomString.js";
const data = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
type: (
_generator?.integer ?? __typia_transform__randomInteger._randomInteger
)({
type: "integer",
}),
number: __typia_transform__randomPick._randomPick([
() => undefined,
() =>
(_generator?.number ?? __typia_transform__randomNumber._randomNumber)({
type: "number",
exclusiveMinimum: 19,
maximum: 100,
}),
])(),
string: (
_generator?.string ?? __typia_transform__randomString._randomString
)({
type: "string",
minLength: 3,
}),
pattern: (
_generator?.pattern ?? __typia_transform__randomPattern._randomPattern
)(new RegExp("^[a-z]+$")),
format: __typia_transform__randomPick._randomPick([
() => null,
() =>
(
_generator?.datetime ??
__typia_transform__randomFormatDatetime._randomFormatDatetime
)(),
])(),
});
let _generator;
return (generator) => {
_generator = generator;
return _ro0();
};
})()();
console.log(data);
Customization
undefined
export function random<T>(g?: IRandomGenerator): Resolved<T>;
undefined
import { OpenApi } from "@samchon/openapi";
/**
* Interface for generating random values for various data types.
*
* `IRandomGenerator` defines the contract for generating random values that can
* be used by typia for creating mock data, testing scenarios, and random value
* generation based on JSON schema constraints.
*
* This interface supports generating random values for:
*
* - Basic types (boolean, number, integer, bigint, string, array)
* - String format patterns (email, URL, UUID, etc.)
* - Date and time formats
* - Various address and identifier formats
*
* @author Jeongho Nam - https://github.com/samchon
* @example
* ```typescript
* const generator: IRandomGenerator = {
* boolean: () => Math.random() > 0.5,
* number: (schema) => Math.random() * (schema.maximum ?? 100),
* string: (schema) => "example-string",
* email: () => "test@example.com",
* // ... implement other methods
* };
* ```;
*/
export interface IRandomGenerator {
// REGULAR DATA TYPES
/**
* Generates a random boolean value.
*
* @returns Random boolean value or undefined
*/
boolean(): boolean | undefined;
/**
* Generates a random number based on JSON schema constraints.
*
* @param schema JSON schema with number constraints (min, max, etc.)
* @returns Random number within the specified constraints
*/
number(schema: OpenApi.IJsonSchema.INumber): number;
/**
* Generates a random integer based on JSON schema constraints.
*
* @param schema JSON schema with integer constraints (min, max, etc.)
* @returns Random integer within the specified constraints
*/
integer(schema: OpenApi.IJsonSchema.IInteger): number;
/**
* Generates a random bigint based on JSON schema constraints.
*
* @param schema JSON schema with integer constraints (min, max, etc.)
* @returns Random bigint within the specified constraints
*/
bigint(schema: OpenApi.IJsonSchema.IInteger): bigint;
/**
* Generates a random string based on JSON schema constraints.
*
* @param schema JSON schema with string constraints (minLength, maxLength,
* pattern, etc.)
* @returns Random string matching the specified constraints
*/
string(schema: OpenApi.IJsonSchema.IString): string;
/**
* Generates a random array with elements created by the provided generator
* function.
*
* @param schema Array schema with element generator function
* @returns Random array with generated elements
*/
array<T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
element: (index: number, count: number) => T;
},
): T[];
/**
* Generates a random string matching the given regular expression pattern.
*
* @param regex Regular expression pattern to match
* @returns Random string matching the pattern
*/
pattern(regex: RegExp): string;
//----
// STRING FORMATS
//----
// SPECIAL CHARACTER FORMATS
/**
* Generates a random base64-encoded byte string.
*
* @returns Random base64 string
*/
byte(): string;
/**
* Generates a random password string.
*
* @returns Random password
*/
password(): string;
/**
* Generates a random regular expression pattern string.
*
* @returns Random regex pattern
*/
regex(): string;
/**
* Generates a random UUID (Universally Unique Identifier).
*
* @returns Random UUID string in standard format
*/
uuid(): string;
// ADDRESS AND IDENTIFIER FORMATS
/**
* Generates a random email address.
*
* @returns Random email address
*/
email(): string;
/**
* Generates a random hostname.
*
* @returns Random hostname
*/
hostname(): string;
/**
* Generates a random internationalized email address.
*
* @returns Random IDN email address
*/
idnEmail(): string;
/**
* Generates a random internationalized hostname.
*
* @returns Random IDN hostname
*/
idnHostname(): string;
/**
* Generates a random IRI (Internationalized Resource Identifier).
*
* @returns Random IRI
*/
iri(): string;
/**
* Generates a random IRI reference.
*
* @returns Random IRI reference
*/
iriReference(): string;
/**
* Generates a random IPv4 address.
*
* @returns Random IPv4 address
*/
ipv4(): string;
/**
* Generates a random IPv6 address.
*
* @returns Random IPv6 address
*/
ipv6(): string;
/**
* Generates a random URI (Uniform Resource Identifier).
*
* @returns Random URI
*/
uri(): string;
/**
* Generates a random URI reference.
*
* @returns Random URI reference
*/
uriReference(): string;
/**
* Generates a random URI template.
*
* @returns Random URI template
*/
uriTemplate(): string;
/**
* Generates a random URL (Uniform Resource Locator).
*
* @returns Random URL
*/
url(): string;
// DATE AND TIME FORMATS
/**
* Generates a random datetime string in ISO 8601 format.
*
* @param props Optional constraints for minimum and maximum timestamp values
* @returns Random datetime string
*/
datetime(props?: { minimum?: number; maximum?: number }): string;
/**
* Generates a random date string in ISO 8601 format (YYYY-MM-DD).
*
* @param props Optional constraints for minimum and maximum timestamp values
* @returns Random date string
*/
date(props?: { minimum?: number; maximum?: number }): string;
/**
* Generates a random time string in ISO 8601 format (HH:MM:SS).
*
* @returns Random time string
*/
time(): string;
/**
* Generates a random duration string in ISO 8601 format.
*
* @returns Random duration string
*/
duration(): string;
// JSON POINTER FORMATS
/**
* Generates a random JSON pointer string.
*
* @returns Random JSON pointer
*/
jsonPointer(): string;
/**
* Generates a random relative JSON pointer string.
*
* @returns Random relative JSON pointer
*/
relativeJsonPointer(): string;
}
export namespace IRandomGenerator {
/**
* Map of custom generators for different data types.
*
* This interface allows customization of random generation for specific types
* when they have certain schema properties or constraints.
*
* @example
* ```typescript
* const generator: Partial<IRandomGenerator> = {
* string: (schema) => {
* if ((schema as any)["x-typia-monetary"] === "dollar") {
* return "$" + Math.floor(Math.random() * 1000);
* }
* return "default-string";
* },
* number: (schema) => {
* if ((schema as any)["x-typia-powerOf"] !== undefined) {
* const powerOf = (schema as any)["x-typia-powerOf"];
* return Math.pow(powerOf, Math.random() * 10 + 1);
* }
* return Math.random() * 100;
* }
* };
* ```;
*/
export interface CustomMap {
/**
* Custom string generator that can handle special string formats based on
* schema properties.
*/
string?: (
schema: OpenApi.IJsonSchema.IString & Record<string, any>,
) => string;
/**
* Custom number generator that can handle special number constraints based
* on schema properties.
*/
number?: (
schema: OpenApi.IJsonSchema.INumber & Record<string, any>,
) => number;
/**
* Custom integer generator that can handle special integer constraints
* based on schema properties.
*/
integer?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => number;
/**
* Custom bigint generator that can handle special bigint constraints based
* on schema properties.
*/
bigint?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => bigint;
/**
* Custom boolean generator that can handle special boolean constraints
* based on schema properties.
*/
boolean?: (schema: Record<string, any>) => boolean | undefined;
/**
* Custom array generator that can handle special array constraints based on
* schema properties.
*/
array?: <T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
element: (index: number, count: number) => T;
} & Record<string, any>,
) => T[];
}
}
undefined
export type Customizable = {
number: number;
string: string;
bigint: bigint;
};
undefined
import { Equal } from "./typings/Equal";
import { IsTuple } from "./typings/IsTuple";
import { NativeClass } from "./typings/NativeClass";
import { ValueOf } from "./typings/ValueOf";
/**
* Resolved type that erases every method.
*
* `Resolved` is a TMP (Type Meta Programming) type which converts its argument
* as a resolved type that erases every method property.
*
* If the target argument is a built-in class which returns its origin primitive
* type through the `valueOf()` method like the `String` or `Number`, its return
* type will be the `string` or `number`. Otherwise, if the built-in class does
* not have the `valueOf()` method, the return type will be the same as the
* target argument.
*
* Otherwise, if the target argument is a type of custom class, all of its
* custom methods will be erased and its prototype will be changed to the
* primitive `object`. Therefore, the return type of the TMP type will finally
* be the resolved object.
*
* Before | After
* ------------------------|---------------------------------------- `Boolean` |
* `boolean` `Number` | `number` `BigInt` | `bigint` `String` | `string` `Class`
* | `interface` Native Class or Others | No change
*
* @author Jeongho Nam - https://github.com/samchon
* @author Kyungsu Kang - https://github.com/kakasoo
* @template T Target argument type.
*/
export type Resolved<T> =
Equal<T, ResolvedMain<T>> extends true ? T : ResolvedMain<T>;
type ResolvedMain<T> = T extends [never]
? never // (special trick for jsonable | null) type
: ValueOf<T> extends boolean | number | bigint | string
? ValueOf<T>
: T extends Function
? never
: T extends object
? ResolvedObject<T>
: ValueOf<T>;
type ResolvedObject<T extends object> =
T extends Array<infer U>
? IsTuple<T> extends true
? ResolvedTuple<T>
: ResolvedMain<U>[]
: T extends Set<infer U>
? Set<ResolvedMain<U>>
: T extends Map<infer K, infer V>
? Map<ResolvedMain<K>, ResolvedMain<V>>
: T extends WeakSet<any> | WeakMap<any, any>
? never
: T extends NativeClass
? T
: {
[P in keyof T]: ResolvedMain<T[P]>;
};
type ResolvedTuple<T extends readonly any[]> = T extends []
? []
: T extends [infer F]
? [ResolvedMain<F>]
: T extends [infer F, ...infer Rest extends readonly any[]]
? [ResolvedMain<F>, ...ResolvedTuple<Rest>]
: T extends [(infer F)?]
? [ResolvedMain<F>?]
: T extends [(infer F)?, ...infer Rest extends readonly any[]]
? [ResolvedMain<F>?, ...ResolvedTuple<Rest>]
: [];
You can add custom type tags for random data generation.
As above IRandomGenerator.CustomMap
has a little bit complicate type, it may hard to understand for newcomers. However, such newcomers may easily understand, how to customize the random generation, just by reading the following example.
Just define custom type tags like below, then everything would be done.
For reference, when defining custom type tag, typia
enforces user to define validate
function literal for type safety. Never forget it when you define custom type tags for random generation. Such validation logic definition may enhance your random data generator logic when combining with typia.assert<T>()
function.
TypeScript Source Code
import typia from "typia";
import { _randomNumber } from "typia/lib/internal/_randomNumber.js";
import { _randomString } from "typia/lib/internal/_randomString.js";
const data: TagCustom = typia.random<TagCustom>({
string: (schema) => {
if ((schema as any)["x-typia-monetary"] === "dollar")
return "$" + Math.floor(Math.random() * 1_000);
else if ((schema as any)["x-typia-postfix"] !== undefined)
return _randomString(schema) + (schema as any)["x-typia-postfix"];
return _randomString(schema);
},
number: (schema) => {
if ((schema as any)["x-typia-powerOf"] !== undefined) {
const powerOf = (schema as any)["x-typia-powerOf"];
return Math.pow(powerOf, Math.floor(Math.random() * 10) + 1);
}
return _randomNumber(schema);
},
});
console.log(data);
interface TagCustom {
id: string & typia.tags.Format<"uuid">;
dollar: string & Dollar;
postfix: string & Postfix<"abcd">;
powerOf: number & PowerOf<2>;
}
type Dollar = typia.tags.TagBase<{
kind: "monetary";
target: "string";
value: "dollar";
validate: `$input[0] === "$" && !isNaN(Number($input.substring(1).split(",").join("")))`;
schema: {
"x-typia-monetary": "dollar";
};
}>;
type Postfix<Value extends string> = typia.tags.TagBase<{
kind: "postfix";
target: "string";
value: Value;
validate: `$input.endsWith("${Value}")`;
schema: {
"x-typia-postfix": Value;
};
}>;
type PowerOf<Value extends number> = typia.tags.TagBase<{
kind: "powerOf";
target: "number";
value: Value;
validate: `(() => {
const denominator: number = Math.log(${Value});
const value: number = Math.log($input) / denominator;
return Math.abs(value - Math.round(value)) < 0.00000001;
})()`;
schema: {
"x-typia-powerOf": Value;
};
}>;
Compiled JavaScript File
import typia from "typia";
import * as __typia_transform__randomFormatUuid from "typia/lib/internal/_randomFormatUuid.js";
import * as __typia_transform__randomNumber from "typia/lib/internal/_randomNumber.js";
import { _randomNumber } from "typia/lib/internal/_randomNumber.js";
import * as __typia_transform__randomString from "typia/lib/internal/_randomString.js";
import { _randomString } from "typia/lib/internal/_randomString.js";
const data = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
id: (
_generator?.uuid ?? __typia_transform__randomFormatUuid._randomFormatUuid
)(),
dollar: (
_generator?.string ?? __typia_transform__randomString._randomString
)({
type: "string",
"x-typia-monetary": "dollar",
}),
postfix: (
_generator?.string ?? __typia_transform__randomString._randomString
)({
type: "string",
"x-typia-postfix": "abcd",
}),
powerOf: (
_generator?.number ?? __typia_transform__randomNumber._randomNumber
)({
type: "number",
"x-typia-powerOf": 2,
}),
});
let _generator;
return (generator) => {
_generator = generator;
return _ro0();
};
})()({
string: (schema) => {
if (schema["x-typia-monetary"] === "dollar")
return "$" + Math.floor(Math.random() * 1_000);
else if (schema["x-typia-postfix"] !== undefined)
return _randomString(schema) + schema["x-typia-postfix"];
return _randomString(schema);
},
number: (schema) => {
if (schema["x-typia-powerOf"] !== undefined) {
const powerOf = schema["x-typia-powerOf"];
return Math.pow(powerOf, Math.floor(Math.random() * 10) + 1);
}
return _randomNumber(schema);
},
});
console.log(data);