typia.random โ make up a value that satisfies the type
function random<T>(generator?: Partial<IRandomGenerator>): Resolved<T>;
function createRandom<T>(generator?: Partial<IRandomGenerator>): () => Resolved<T>;typia.random<T> returns a value that satisfies T. Use it for test fixtures, seeding databases, or building demos without writing factory functions by hand.
It honors satisfiable type tags you put on the type: tags.Format<"email"> will produce an email, tags.Minimum<0> & tags.Maximum<100> will pick a number in that range, tags.MaxLength<8> will cap a stringโs length.
Numeric tags.MultipleOf<N> constraints choose an integer quotient and construct the result with finite-decimal arithmetic. One-sided fallback ranges stay in value units before that snapping step, and a bounded range with no valid multiple throws instead of retrying indefinitely.
Length tags combine with a Format or Pattern on the same string: tags.Format<"email"> & tags.MinLength<40> produces a 40-character email, and tags.Pattern<"^[0-9]+$"> & tags.MaxLength<3> produces a short digit string. A combination no string can satisfy โ tags.Format<"email"> & tags.MaxLength<3>, or a pattern whose fixed length conflicts with the bound โ throws instead of emitting a value its own validator would reject.
Without length tags, plain strings use length 5..10, and non-recursive arrays use length 1..6. Explicit constraints still win: tags.MaxLength<0> can produce "", and tags.MaxItems<0> produces an empty array. Recursive arrays receive recursive: true on the array generator props and use length 0..2 by default so graph-shaped data can terminate. A direct recursive array alias or owner edge, and any array that must serve as the recursive depth cutoff, cannot also require a positive minimum length; typia.random rejects that combination at compile time because the cutoff may need to emit an empty array.
Recursion terminates only where the depth cutoff has an escape to take: an array, set, or map that may be empty, a tuple rest (...T[]) that spreads zero elements, a nullable edge that may become null, an optional or index-signature property that may be dropped, or a union with at least one finite variant. A recursive type whose every cycle is a required, non-nullable, non-container value โ interface INode { next: INode } or a mutual A โ B โ A object cycle โ has no finite value to generate, so typia.random rejects it at compile time instead of overflowing the stack. Give the cycle any one escape (next: INode | null, next?: INode, or next: INode[]) to make it satisfiable.
First example
import typia, { tags } from "typia";
interface User {
id: string & tags.Format<"uuid">;
email: string & tags.Format<"email">;
age: number & tags.Type<"uint32"> & tags.Minimum<19> & tags.Maximum<99>;
hobbies: string[];
}
const user = typia.random<User>();
// e.g.
// {
// id: "b6e0โฆ",
// email: "abc@example.com",
// age: 47,
// hobbies: ["wzPwLvO", "u_a-mqQ"],
// }TypeScript Source
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
import typia from "typia";
import * as _randomFormatEmail_1 from "typia/lib/internal/_randomFormatEmail";
import * as _randomFormatUuid_1 from "typia/lib/internal/_randomFormatUuid";
import * as _randomInteger_1 from "typia/lib/internal/_randomInteger";
const member = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
id: (_generator?.uuid ?? _randomFormatUuid_1._randomFormatUuid)(),
email: (_generator?.email ?? _randomFormatEmail_1._randomFormatEmail)(),
age: (_generator?.integer ?? _randomInteger_1._randomInteger)({
type: "integer",
minimum: 0,
exclusiveMinimum: 19,
maximum: 100,
}),
});
let _generator;
return (generator_1) => {
_generator = generator_1;
return _ro0();
};
})()();
console.log(member);undefined
export function random<T>(g?: Partial<IRandomGenerator>): Resolved<T>;undefined
import { OpenApi } from "../openapi/OpenApi";
/**
* Random value generator interface for typia.
*
* `IRandomGenerator` defines methods for generating random values of various
* types. Used by `typia.random<T>()` for mock data generation.
*
* Every method is replaceable: `typia.random<T>()` accepts a
* `Partial<IRandomGenerator>` and falls back to its built-in generator for each
* method that is not supplied. The optional `pick` hook selects lazy candidates
* independently of primitive-value methods. The generated code passes the
* `minLength` and `maxLength` bounds of a property to the string format and
* pattern generators when the property carries length tags; a custom generator
* has to honor them for its value to pass the generated validator.
*
* @author Jeongho Nam - https://github.com/samchon
*
* @evidence contracts/common.md#principled-implementation The interface lists primitive, array and string-format methods plus an optional generic candidate selector that the random programmer can request, so a caller can replace any of them through `Partial<IRandomGenerator>`. Each signature takes the schema or bounds the generated code actually passes: JSON schemas for atomics, length bounds for formats and patterns, and epoch bounds for dates. The format methods declare the optional length bounds that the generated code forwards.
* @evidence contracts/common.md#clear-and-simple-design One flat method table with no inheritance; the two small bound records and the custom map are in the namespace because only these signatures use them.
* @evidence contracts/common.md#prohibited-implementation-shortcuts Replacement happens through the supplied generator object; the declaration does not patch the built-in generator. It cannot make a custom generator honor the bounds it receives, which the comment states as the caller's duty.
* @evidence contracts/common.md#meaningful-documentation The comment states the purpose, the replacement and fallback rule and the length-bound duty, and each method has its own comment.
*/
export interface IRandomGenerator {
/**
* Selects one candidate while generating a union or other alternative.
*
* The candidates are lazy generation functions when used by typia. Return an
* element of the supplied array; generation invokes only that selected
* element. The hook receives the supplied generator object as its receiver,
* so a stateful selector can keep state on that object. Omitting this hook
* preserves uniform built-in selection. It does not change the source of
* primitive, format or pattern generators.
*
* @evidence contracts/common.md#principled-implementation A generic selector returns one of the supplied candidates without requiring knowledge of its value type. The native random programmer supplies lazy callbacks, so selection decides a branch before generation executes it; existing leaf integer customization remains independent.
* @evidence contracts/common.md#clear-and-simple-design One optional method extends the existing customization table. Its generic result has the candidate element type, and no global seeded-generator state is introduced.
* @evidence contracts/common.md#prohibited-implementation-shortcuts Consumers pass the selector through the supported generator object. The declaration requires an actual candidate and does not patch platform randomness or assume a fixture branch.
* @evidence contracts/common.md#meaningful-documentation The prose explains lazy candidates, required membership, uniform fallback and the distinction from primitive/format entropy.
*/
pick?<T>(array: T[]): T;
/**
* Generates a random boolean.
*
* @evidence contracts/common.md#principled-implementation Returns a boolean or undefined, the same optional boolean the generated code accepts for a boolean leaf, and takes no argument because a boolean has no constraints to forward.
* @evidence contracts/common.md#clear-and-simple-design A single parameterless method.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only; the built-in uses Math.random and this contract does not name it.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states what is generated.
*/
boolean(): boolean | undefined;
/**
* Generates a random number within schema constraints.
*
* @evidence contracts/common.md#principled-implementation Takes the OpenAPI number schema so a generator sees minimum, maximum, exclusive bounds and multipleOf, and returns a number.
* @evidence contracts/common.md#clear-and-simple-design One method with the schema as its only parameter.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only; constraint handling belongs to the generator that implements it.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
number(schema: OpenApi.IJsonSchema.INumber): number;
/**
* Generates a random integer within schema constraints.
*
* @evidence contracts/common.md#principled-implementation Takes the integer schema and returns a JavaScript number. Representable integers can exceed the safe-integer range, which guarantees consecutive integer precision rather than bounding every representable integer.
* @evidence contracts/common.md#clear-and-simple-design One method with the schema as its only parameter.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
integer(schema: OpenApi.IJsonSchema.IInteger): number;
/**
* Generates a random bigint within schema constraints.
*
* @evidence contracts/common.md#principled-implementation The integer-schema argument carries numeric bounds and the return type carries an arbitrary-precision integer. The bigint result does not recover precision already lost in a schema number; the implementing generator owns constraint handling.
* @evidence contracts/common.md#clear-and-simple-design One method, parallel to integer but with a bigint result.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
bigint(schema: OpenApi.IJsonSchema.IInteger): bigint;
/**
* Generates a random string within schema constraints.
*
* @evidence contracts/common.md#principled-implementation Takes the string schema, which carries length, format and pattern keywords, and returns a string; this is the fallback used when no more specific format or pattern generator applies.
* @evidence contracts/common.md#clear-and-simple-design One method; format and pattern generators are separate methods because the generated code selects them first.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
string(schema: OpenApi.IJsonSchema.IString): string;
/**
* Generates a random array with elements from the generator function.
*
* @evidence contracts/common.md#principled-implementation The parameter is the array schema without `items`, an element callback that receives the index and the chosen count so the generator can build elements after choosing a length, and an optional recursion flag that lets a custom generator shorten cyclic structures so generation terminates. For unique arrays the chosen count is a target; duplicate exhaustion may produce fewer elements above the minimum.
* @evidence contracts/common.md#clear-and-simple-design The callback is passed in instead of a items schema because the generated code owns how elements are built.
* @evidence contracts/common.md#prohibited-implementation-shortcuts The recursion flag is a documented hint, and the contract does not guarantee termination for a generator that ignores it.
* @evidence contracts/common.md#meaningful-documentation The one-line comment and the flag's comment state the callback role and the termination purpose.
*/
array<T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
/** Generates an element after the array length has been chosen. */
element: (index: number, count: number) => T;
/**
* Whether this array lies on a recursive type's cycle. Custom generators
* can bias toward fewer (or zero) elements so graph-shaped data
* terminates instead of growing without bound.
*/
recursive?: boolean;
},
): T[];
/**
* Generates a random string matching the regex pattern.
*
* @param regex Pattern the string must match
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Takes the compiled RegExp, which the generated code builds from the schema pattern, plus optional length bounds so a pattern combined with length tags can be generated at an acceptable length.
* @evidence contracts/common.md#clear-and-simple-design One method with the pattern first and an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only; matching the expression and counting characters are done by the implementation.
* @evidence contracts/common.md#meaningful-documentation The comment documents both parameters.
*/
pattern(regex: RegExp, props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a Base64 string for the `byte` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a Base64 string for the byte format; the built-in implementation produces lengths that are multiples of four, so the optional length bounds are mapped to such lengths.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
byte(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a string for the documentation-only `password` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation The password format has no grammar, so any string within the bounds is acceptable; the method returns a string.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and states that it is documentation only.
*/
password(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a source string for the `regex` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation The regex format requires a source string that compiles, and the built-in generator emits only literal characters, which are valid in any expression, so a string of any length is acceptable.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
regex(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a UUID string for the `uuid` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a UUID in the textual 8-4-4-4-12 form; the bounds parameter exists because a length tag could constrain it, and the fixed length of that form means a conflicting bound can only be unsatisfiable.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uuid(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an email address for the `email` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an address of local part, at sign and domain with a top-level label; the bounds parameter lets the local part absorb the requested length.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
email(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a hostname for the `hostname` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns dot-joined labels; the bounds are realized by splitting the length across labels, within the 63-character label and 253-character total limits of a hostname.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
hostname(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an internationalized email address for the `idn-email` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an internationalized email address; its checker needs a top-level label of at least two characters, which the built-in generator accounts for when it spends length.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
idnEmail(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an internationalized hostname for the `idn-hostname` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an internationalized hostname with the same label structure as hostname, so a single label is valid.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
idnHostname(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an internationalized resource identifier for the `iri` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an internationalized resource identifier; the built-in generator emits an absolute https URL, which is also a valid IRI.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
iri(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an IRI reference for the `iri-reference` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an IRI reference; an absolute IRI is also a valid reference, which is why the built-in generator can reuse its URL form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
iriReference(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an IPv4 address for the `ipv4` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a dotted quad of four octets of one to three digits, each at most 255; the bounds select how many digits each octet uses, within the 7 to 15 character range of the form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
ipv4(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an IPv6 address for the `ipv6` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an IPv6 address; the built-in generator covers the compressed, full eight-group and IPv4-suffixed forms so lengths from two to the longest form are expressible.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
ipv6(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URI for the `uri` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a URI; an absolute https URL is a valid URI, so the built-in generator reuses its URL builder.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uri(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URI reference for the `uri-reference` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a URI reference; absolute URIs are valid references.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uriReference(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URI template for the `uri-template` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a URI template; a URL without expressions is a valid template.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uriTemplate(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URL for the `url` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an absolute https URL whose path segment absorbs extra requested length, since a URL's path is unbounded.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
url(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an RFC 3339 date-time string for the `date-time` format.
*
* @param props Epoch millisecond bounds, and the length bounds of the
* property when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an RFC 3339 date-time; the parameter combines epoch bounds, which select the instant, with length bounds, which select the fractional-second digits, since a date-time has few valid lengths.
* @evidence contracts/common.md#clear-and-simple-design One method whose parameter is the intersection of the two bound records.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the combined bounds.
*/
datetime(
props?: IRandomGenerator.IEpochProps & IRandomGenerator.ILengthProps,
): string;
/**
* Generates a `YYYY-MM-DD` date string for the `date` format.
*
* @param props Epoch millisecond bounds, and the length bounds of the
* property when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a calendar date; epoch bounds select the day and length bounds are accepted for uniformity, though a date has one length.
* @evidence contracts/common.md#clear-and-simple-design One method with the same parameter type as datetime.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the combined bounds.
*/
date(
props?: IRandomGenerator.IEpochProps & IRandomGenerator.ILengthProps,
): string;
/**
* Generates an RFC 3339 time string for the `time` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an RFC 3339 time with a mandatory offset; the built-in generator reaches every length it can express by choosing fraction digits and offset form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
time(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an ISO 8601 duration string for the `duration` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an ISO 8601 duration; with no bound it composes designators, and with a bound a single year designator with an unbounded digit count expresses any length from three up.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
duration(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a JSON pointer for the `json-pointer` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a JSON pointer; the built-in generator uses a fixed components prefix with a variable token and falls back to the empty pointer or a one-token pointer when the bound is shorter than that prefix.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
jsonPointer(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a relative JSON pointer for the `relative-json-pointer` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a relative JSON pointer, a non-negative integer optionally followed by a hash or a pointer; a single digit is the shortest form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
relativeJsonPointer(props?: IRandomGenerator.ILengthProps): string;
}
export namespace IRandomGenerator {
/**
* String length bounds that the generated code forwards to a generator.
*
* @evidence contracts/common.md#principled-implementation Two optional numbers mirror the schema's minLength and maxLength; they are optional because either side may be open.
* @evidence contracts/common.md#clear-and-simple-design A separate record shared by every format method instead of repeated inline literals.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A data record; it does not validate that the bounds are consistent.
* @evidence contracts/common.md#meaningful-documentation The comment and field comments say they are forwarded by the generated code when the property has length tags.
*/
export interface ILengthProps {
/** Minimum number of characters, when the property has a `minLength`. */
minLength?: number;
/** Maximum number of characters, when the property has a `maxLength`. */
maxLength?: number;
}
/**
* Epoch millisecond bounds of a generated date or date-time.
*
* @evidence contracts/common.md#principled-implementation Two optional epoch millisecond numbers bound the instant of a date or date-time; either side may be open.
* @evidence contracts/common.md#clear-and-simple-design A separate record because only date and datetime use it.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A data record; it does not validate the order of the bounds.
* @evidence contracts/common.md#meaningful-documentation The comment and field comments state that the unit is milliseconds since the epoch.
*/
export interface IEpochProps {
/** Earliest instant, in milliseconds since the epoch. */
minimum?: number;
/** Latest instant, in milliseconds since the epoch. */
maximum?: number;
}
/**
* Custom generators keyed by the schema kind they would replace.
*
* @evidence contracts/common.md#principled-implementation Each optional member is keyed by a schema kind and receives that kind's schema extended with arbitrary extra keys, so a custom generator can read vendor keywords; the return type matches the kind's value type.
* @evidence contracts/common.md#clear-and-simple-design Six optional members, one per kind that has a schema-driven generator. No code in this repository reads the map, so it documents an extension shape and not a behavior verified here.
* @evidence contracts/common.md#prohibited-implementation-shortcuts The map supplies replacements by value and patches nothing.
* @evidence contracts/common.md#meaningful-documentation The comment names the keyed-by-kind role and each member names the schema it receives.
*/
export interface CustomMap {
/**
* Custom string generator, called with the string schema.
*
* @evidence contracts/common.md#principled-implementation A function from the string schema, plus extra keys, to a string.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
string?: (
schema: OpenApi.IJsonSchema.IString & Record<string, any>,
) => string;
/**
* Custom number generator, called with the number schema.
*
* @evidence contracts/common.md#principled-implementation A function from the number schema, plus extra keys, to a number.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
number?: (
schema: OpenApi.IJsonSchema.INumber & Record<string, any>,
) => number;
/**
* Custom integer generator, called with the integer schema.
*
* @evidence contracts/common.md#principled-implementation A function from the integer schema, plus extra keys, to a number.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
integer?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => number;
/**
* Custom bigint generator, called with the integer schema.
*
* @evidence contracts/common.md#principled-implementation A function from the integer schema, plus extra keys, to a bigint.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
bigint?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => bigint;
/**
* Custom boolean generator, called with the schema record.
*
* @evidence contracts/common.md#principled-implementation A function from a free-form schema record to an optional boolean, the same result type as the interface's boolean method.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
boolean?: (schema: Record<string, any>) => boolean | undefined;
/**
* Custom array generator, called with the array schema and an element
* generator.
*
* @evidence contracts/common.md#principled-implementation A generic function from the array schema, the element callback and the recursion flag, plus extra keys, to an array of the element type.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives, and the recursion flag has its own comment.
*/
array?: <T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
/** Generates an element after the array length has been chosen. */
element: (index: number, count: number) => T;
/**
* Whether this array lies on a recursive type's cycle. Custom
* generators can bias toward fewer (or zero) elements so graph-shaped
* data terminates instead of growing without bound.
*/
recursive?: boolean;
} & Record<string, any>,
) => T[];
}
}undefined
import { Equal } from "./internal/Equal";
import { IsTupleLike } from "./internal/IsTupleLike";
import { NativeClass } from "./internal/NativeClass";
import { ValueOf } from "./internal/ValueOf";
/**
* Converts a type to its resolved form by mapping callable values to never.
*
* `Resolved<T>` transforms classes to plain objects, extracts primitive values
* from boxed types (Booleanโboolean, Numberโnumber, Stringโstring), and
* recursively processes nested public properties. Arrays, tuples, Set and Map
* retain their container shape while their contents are resolved recursively,
* including readonly containers. Date and other supported native classes pass
* through unchanged; WeakSet and WeakMap become `never`.
*
* @author Jeongho Nam - https://github.com/samchon
* @author Kyungsu Kang - https://github.com/kakasoo
*
* @template T Target type to resolve
*
* @evidence contracts/common.md#principled-implementation Conditional types unwrap boxed primitives, map callable values to never and recursively resolve public properties and array, tuple, Set and Map contents. Supported native classes pass through after the container branches; weak collections become never. Broad unknown/object inputs remain unchanged. TupleStack preserves a revisited tuple-rest identity rather than imposing a depth limit, and arrays bypass the Equal comparison to avoid eager recursive-alias evaluation.
* @evidence contracts/common.md#clear-and-simple-design A thin alias chooses between the original and the resolved form and delegates structure-specific work to ResolvedMain, ResolvedObject and ResolvedArray.
* @evidence contracts/common.md#prohibited-implementation-shortcuts It is a structural mapping over the type with no consumer names, casts or runtime code.
* @evidence contracts/common.md#meaningful-documentation The comment states what is resolved and which categories are preserved; recursion and tuple guards are explained in line comments at their private declarations.
*/
export type Resolved<T> = unknown extends T
? T
: object extends T
? T
: T extends readonly unknown[]
? ResolvedMain<T> // avoid eagerly comparing recursive tuple rest aliases
: Equal<T, ResolvedMain<T>> extends true
? T
: ResolvedMain<T>;
// TupleStack closes recursive tuple rest cycles without limiting other nesting.
type ResolvedMain<T, TupleStack = never> = 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, TupleStack>
: ValueOf<T>;
type ResolvedObject<T extends object, TupleStack> =
T extends Array<infer U>
? IsTupleLike<T> extends true
? T extends TupleStack
? T
: ResolvedArray<T, TupleStack | T>
: Array<ResolvedMain<U, TupleStack>>
: T extends ReadonlyArray<infer U>
? IsTupleLike<T> extends true
? T extends TupleStack
? T
: ResolvedArray<T, TupleStack | T>
: ReadonlyArray<ResolvedMain<U, TupleStack>>
: T extends Set<infer U>
? Set<ResolvedMain<U, TupleStack>>
: T extends Map<infer K, infer V>
? Map<ResolvedMain<K, TupleStack>, ResolvedMain<V, TupleStack>>
: T extends ReadonlyMap<infer K, infer V>
? ReadonlyMap<
ResolvedMain<K, TupleStack>,
ResolvedMain<V, TupleStack>
>
: T extends ReadonlySet<infer U>
? ReadonlySet<ResolvedMain<U, TupleStack>>
: T extends WeakSet<any> | WeakMap<any, any>
? never
: T extends NativeClass
? T
: {
[P in keyof T]: ResolvedMain<T[P], TupleStack>;
};
type ResolvedArray<T extends readonly unknown[], TupleStack> = {
[P in keyof T]: ResolvedMain<T[P], TupleStack>;
};Reusable factory
const randomUser = typia.createRandom<User>();
const a = randomUser();
const b = randomUser();
// Pass a custom generator at factory creation:
const customRandomUser = typia.createRandom<User>(customGenerator);
const c = customRandomUser();The factory takes the generator once at creation and returns a zero-argument function. (If you need different generators per call, just create more factories โ theyโre cheap.)
undefined
export function createRandom<T>(g?: Partial<IRandomGenerator>): () => Resolved<T>;undefined
import { OpenApi } from "../openapi/OpenApi";
/**
* Random value generator interface for typia.
*
* `IRandomGenerator` defines methods for generating random values of various
* types. Used by `typia.random<T>()` for mock data generation.
*
* Every method is replaceable: `typia.random<T>()` accepts a
* `Partial<IRandomGenerator>` and falls back to its built-in generator for each
* method that is not supplied. The optional `pick` hook selects lazy candidates
* independently of primitive-value methods. The generated code passes the
* `minLength` and `maxLength` bounds of a property to the string format and
* pattern generators when the property carries length tags; a custom generator
* has to honor them for its value to pass the generated validator.
*
* @author Jeongho Nam - https://github.com/samchon
*
* @evidence contracts/common.md#principled-implementation The interface lists primitive, array and string-format methods plus an optional generic candidate selector that the random programmer can request, so a caller can replace any of them through `Partial<IRandomGenerator>`. Each signature takes the schema or bounds the generated code actually passes: JSON schemas for atomics, length bounds for formats and patterns, and epoch bounds for dates. The format methods declare the optional length bounds that the generated code forwards.
* @evidence contracts/common.md#clear-and-simple-design One flat method table with no inheritance; the two small bound records and the custom map are in the namespace because only these signatures use them.
* @evidence contracts/common.md#prohibited-implementation-shortcuts Replacement happens through the supplied generator object; the declaration does not patch the built-in generator. It cannot make a custom generator honor the bounds it receives, which the comment states as the caller's duty.
* @evidence contracts/common.md#meaningful-documentation The comment states the purpose, the replacement and fallback rule and the length-bound duty, and each method has its own comment.
*/
export interface IRandomGenerator {
/**
* Selects one candidate while generating a union or other alternative.
*
* The candidates are lazy generation functions when used by typia. Return an
* element of the supplied array; generation invokes only that selected
* element. The hook receives the supplied generator object as its receiver,
* so a stateful selector can keep state on that object. Omitting this hook
* preserves uniform built-in selection. It does not change the source of
* primitive, format or pattern generators.
*
* @evidence contracts/common.md#principled-implementation A generic selector returns one of the supplied candidates without requiring knowledge of its value type. The native random programmer supplies lazy callbacks, so selection decides a branch before generation executes it; existing leaf integer customization remains independent.
* @evidence contracts/common.md#clear-and-simple-design One optional method extends the existing customization table. Its generic result has the candidate element type, and no global seeded-generator state is introduced.
* @evidence contracts/common.md#prohibited-implementation-shortcuts Consumers pass the selector through the supported generator object. The declaration requires an actual candidate and does not patch platform randomness or assume a fixture branch.
* @evidence contracts/common.md#meaningful-documentation The prose explains lazy candidates, required membership, uniform fallback and the distinction from primitive/format entropy.
*/
pick?<T>(array: T[]): T;
/**
* Generates a random boolean.
*
* @evidence contracts/common.md#principled-implementation Returns a boolean or undefined, the same optional boolean the generated code accepts for a boolean leaf, and takes no argument because a boolean has no constraints to forward.
* @evidence contracts/common.md#clear-and-simple-design A single parameterless method.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only; the built-in uses Math.random and this contract does not name it.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states what is generated.
*/
boolean(): boolean | undefined;
/**
* Generates a random number within schema constraints.
*
* @evidence contracts/common.md#principled-implementation Takes the OpenAPI number schema so a generator sees minimum, maximum, exclusive bounds and multipleOf, and returns a number.
* @evidence contracts/common.md#clear-and-simple-design One method with the schema as its only parameter.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only; constraint handling belongs to the generator that implements it.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
number(schema: OpenApi.IJsonSchema.INumber): number;
/**
* Generates a random integer within schema constraints.
*
* @evidence contracts/common.md#principled-implementation Takes the integer schema and returns a JavaScript number. Representable integers can exceed the safe-integer range, which guarantees consecutive integer precision rather than bounding every representable integer.
* @evidence contracts/common.md#clear-and-simple-design One method with the schema as its only parameter.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
integer(schema: OpenApi.IJsonSchema.IInteger): number;
/**
* Generates a random bigint within schema constraints.
*
* @evidence contracts/common.md#principled-implementation The integer-schema argument carries numeric bounds and the return type carries an arbitrary-precision integer. The bigint result does not recover precision already lost in a schema number; the implementing generator owns constraint handling.
* @evidence contracts/common.md#clear-and-simple-design One method, parallel to integer but with a bigint result.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
bigint(schema: OpenApi.IJsonSchema.IInteger): bigint;
/**
* Generates a random string within schema constraints.
*
* @evidence contracts/common.md#principled-implementation Takes the string schema, which carries length, format and pattern keywords, and returns a string; this is the fallback used when no more specific format or pattern generator applies.
* @evidence contracts/common.md#clear-and-simple-design One method; format and pattern generators are separate methods because the generated code selects them first.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment says it follows schema constraints.
*/
string(schema: OpenApi.IJsonSchema.IString): string;
/**
* Generates a random array with elements from the generator function.
*
* @evidence contracts/common.md#principled-implementation The parameter is the array schema without `items`, an element callback that receives the index and the chosen count so the generator can build elements after choosing a length, and an optional recursion flag that lets a custom generator shorten cyclic structures so generation terminates. For unique arrays the chosen count is a target; duplicate exhaustion may produce fewer elements above the minimum.
* @evidence contracts/common.md#clear-and-simple-design The callback is passed in instead of a items schema because the generated code owns how elements are built.
* @evidence contracts/common.md#prohibited-implementation-shortcuts The recursion flag is a documented hint, and the contract does not guarantee termination for a generator that ignores it.
* @evidence contracts/common.md#meaningful-documentation The one-line comment and the flag's comment state the callback role and the termination purpose.
*/
array<T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
/** Generates an element after the array length has been chosen. */
element: (index: number, count: number) => T;
/**
* Whether this array lies on a recursive type's cycle. Custom generators
* can bias toward fewer (or zero) elements so graph-shaped data
* terminates instead of growing without bound.
*/
recursive?: boolean;
},
): T[];
/**
* Generates a random string matching the regex pattern.
*
* @param regex Pattern the string must match
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Takes the compiled RegExp, which the generated code builds from the schema pattern, plus optional length bounds so a pattern combined with length tags can be generated at an acceptable length.
* @evidence contracts/common.md#clear-and-simple-design One method with the pattern first and an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only; matching the expression and counting characters are done by the implementation.
* @evidence contracts/common.md#meaningful-documentation The comment documents both parameters.
*/
pattern(regex: RegExp, props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a Base64 string for the `byte` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a Base64 string for the byte format; the built-in implementation produces lengths that are multiples of four, so the optional length bounds are mapped to such lengths.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
byte(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a string for the documentation-only `password` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation The password format has no grammar, so any string within the bounds is acceptable; the method returns a string.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and states that it is documentation only.
*/
password(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a source string for the `regex` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation The regex format requires a source string that compiles, and the built-in generator emits only literal characters, which are valid in any expression, so a string of any length is acceptable.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
regex(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a UUID string for the `uuid` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a UUID in the textual 8-4-4-4-12 form; the bounds parameter exists because a length tag could constrain it, and the fixed length of that form means a conflicting bound can only be unsatisfiable.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uuid(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an email address for the `email` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an address of local part, at sign and domain with a top-level label; the bounds parameter lets the local part absorb the requested length.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
email(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a hostname for the `hostname` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns dot-joined labels; the bounds are realized by splitting the length across labels, within the 63-character label and 253-character total limits of a hostname.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
hostname(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an internationalized email address for the `idn-email` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an internationalized email address; its checker needs a top-level label of at least two characters, which the built-in generator accounts for when it spends length.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
idnEmail(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an internationalized hostname for the `idn-hostname` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an internationalized hostname with the same label structure as hostname, so a single label is valid.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
idnHostname(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an internationalized resource identifier for the `iri` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an internationalized resource identifier; the built-in generator emits an absolute https URL, which is also a valid IRI.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
iri(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an IRI reference for the `iri-reference` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an IRI reference; an absolute IRI is also a valid reference, which is why the built-in generator can reuse its URL form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
iriReference(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an IPv4 address for the `ipv4` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a dotted quad of four octets of one to three digits, each at most 255; the bounds select how many digits each octet uses, within the 7 to 15 character range of the form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
ipv4(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an IPv6 address for the `ipv6` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an IPv6 address; the built-in generator covers the compressed, full eight-group and IPv4-suffixed forms so lengths from two to the longest form are expressible.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
ipv6(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URI for the `uri` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a URI; an absolute https URL is a valid URI, so the built-in generator reuses its URL builder.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uri(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URI reference for the `uri-reference` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a URI reference; absolute URIs are valid references.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uriReference(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URI template for the `uri-template` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a URI template; a URL without expressions is a valid template.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
uriTemplate(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a URL for the `url` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an absolute https URL whose path segment absorbs extra requested length, since a URL's path is unbounded.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
url(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an RFC 3339 date-time string for the `date-time` format.
*
* @param props Epoch millisecond bounds, and the length bounds of the
* property when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an RFC 3339 date-time; the parameter combines epoch bounds, which select the instant, with length bounds, which select the fractional-second digits, since a date-time has few valid lengths.
* @evidence contracts/common.md#clear-and-simple-design One method whose parameter is the intersection of the two bound records.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the combined bounds.
*/
datetime(
props?: IRandomGenerator.IEpochProps & IRandomGenerator.ILengthProps,
): string;
/**
* Generates a `YYYY-MM-DD` date string for the `date` format.
*
* @param props Epoch millisecond bounds, and the length bounds of the
* property when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a calendar date; epoch bounds select the day and length bounds are accepted for uniformity, though a date has one length.
* @evidence contracts/common.md#clear-and-simple-design One method with the same parameter type as datetime.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the combined bounds.
*/
date(
props?: IRandomGenerator.IEpochProps & IRandomGenerator.ILengthProps,
): string;
/**
* Generates an RFC 3339 time string for the `time` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an RFC 3339 time with a mandatory offset; the built-in generator reaches every length it can express by choosing fraction digits and offset form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
time(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates an ISO 8601 duration string for the `duration` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns an ISO 8601 duration; with no bound it composes designators, and with a bound a single year designator with an unbounded digit count expresses any length from three up.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
duration(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a JSON pointer for the `json-pointer` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a JSON pointer; the built-in generator uses a fixed components prefix with a variable token and falls back to the empty pointer or a one-token pointer when the bound is shorter than that prefix.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
jsonPointer(props?: IRandomGenerator.ILengthProps): string;
/**
* Generates a relative JSON pointer for the `relative-json-pointer` format.
*
* @param props Length bounds of the property, when it carries length tags
*
* @evidence contracts/common.md#principled-implementation Returns a relative JSON pointer, a non-negative integer optionally followed by a hash or a pointer; a single digit is the shortest form.
* @evidence contracts/common.md#clear-and-simple-design One method with an optional bounds record.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A declaration only.
* @evidence contracts/common.md#meaningful-documentation The comment names the format and documents the bounds parameter.
*/
relativeJsonPointer(props?: IRandomGenerator.ILengthProps): string;
}
export namespace IRandomGenerator {
/**
* String length bounds that the generated code forwards to a generator.
*
* @evidence contracts/common.md#principled-implementation Two optional numbers mirror the schema's minLength and maxLength; they are optional because either side may be open.
* @evidence contracts/common.md#clear-and-simple-design A separate record shared by every format method instead of repeated inline literals.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A data record; it does not validate that the bounds are consistent.
* @evidence contracts/common.md#meaningful-documentation The comment and field comments say they are forwarded by the generated code when the property has length tags.
*/
export interface ILengthProps {
/** Minimum number of characters, when the property has a `minLength`. */
minLength?: number;
/** Maximum number of characters, when the property has a `maxLength`. */
maxLength?: number;
}
/**
* Epoch millisecond bounds of a generated date or date-time.
*
* @evidence contracts/common.md#principled-implementation Two optional epoch millisecond numbers bound the instant of a date or date-time; either side may be open.
* @evidence contracts/common.md#clear-and-simple-design A separate record because only date and datetime use it.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A data record; it does not validate the order of the bounds.
* @evidence contracts/common.md#meaningful-documentation The comment and field comments state that the unit is milliseconds since the epoch.
*/
export interface IEpochProps {
/** Earliest instant, in milliseconds since the epoch. */
minimum?: number;
/** Latest instant, in milliseconds since the epoch. */
maximum?: number;
}
/**
* Custom generators keyed by the schema kind they would replace.
*
* @evidence contracts/common.md#principled-implementation Each optional member is keyed by a schema kind and receives that kind's schema extended with arbitrary extra keys, so a custom generator can read vendor keywords; the return type matches the kind's value type.
* @evidence contracts/common.md#clear-and-simple-design Six optional members, one per kind that has a schema-driven generator. No code in this repository reads the map, so it documents an extension shape and not a behavior verified here.
* @evidence contracts/common.md#prohibited-implementation-shortcuts The map supplies replacements by value and patches nothing.
* @evidence contracts/common.md#meaningful-documentation The comment names the keyed-by-kind role and each member names the schema it receives.
*/
export interface CustomMap {
/**
* Custom string generator, called with the string schema.
*
* @evidence contracts/common.md#principled-implementation A function from the string schema, plus extra keys, to a string.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
string?: (
schema: OpenApi.IJsonSchema.IString & Record<string, any>,
) => string;
/**
* Custom number generator, called with the number schema.
*
* @evidence contracts/common.md#principled-implementation A function from the number schema, plus extra keys, to a number.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
number?: (
schema: OpenApi.IJsonSchema.INumber & Record<string, any>,
) => number;
/**
* Custom integer generator, called with the integer schema.
*
* @evidence contracts/common.md#principled-implementation A function from the integer schema, plus extra keys, to a number.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
integer?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => number;
/**
* Custom bigint generator, called with the integer schema.
*
* @evidence contracts/common.md#principled-implementation A function from the integer schema, plus extra keys, to a bigint.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
bigint?: (
schema: OpenApi.IJsonSchema.IInteger & Record<string, any>,
) => bigint;
/**
* Custom boolean generator, called with the schema record.
*
* @evidence contracts/common.md#principled-implementation A function from a free-form schema record to an optional boolean, the same result type as the interface's boolean method.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives.
*/
boolean?: (schema: Record<string, any>) => boolean | undefined;
/**
* Custom array generator, called with the array schema and an element
* generator.
*
* @evidence contracts/common.md#principled-implementation A generic function from the array schema, the element callback and the recursion flag, plus extra keys, to an array of the element type.
* @evidence contracts/common.md#clear-and-simple-design One optional member.
* @evidence contracts/common.md#prohibited-implementation-shortcuts A type declaration only.
* @evidence contracts/common.md#meaningful-documentation The one-line comment states the schema it receives, and the recursion flag has its own comment.
*/
array?: <T>(
schema: Omit<OpenApi.IJsonSchema.IArray, "items"> & {
/** Generates an element after the array length has been chosen. */
element: (index: number, count: number) => T;
/**
* Whether this array lies on a recursive type's cycle. Custom
* generators can bias toward fewer (or zero) elements so graph-shaped
* data terminates instead of growing without bound.
*/
recursive?: boolean;
} & Record<string, any>,
) => T[];
}
}undefined
import { Equal } from "./internal/Equal";
import { IsTupleLike } from "./internal/IsTupleLike";
import { NativeClass } from "./internal/NativeClass";
import { ValueOf } from "./internal/ValueOf";
/**
* Converts a type to its resolved form by mapping callable values to never.
*
* `Resolved<T>` transforms classes to plain objects, extracts primitive values
* from boxed types (Booleanโboolean, Numberโnumber, Stringโstring), and
* recursively processes nested public properties. Arrays, tuples, Set and Map
* retain their container shape while their contents are resolved recursively,
* including readonly containers. Date and other supported native classes pass
* through unchanged; WeakSet and WeakMap become `never`.
*
* @author Jeongho Nam - https://github.com/samchon
* @author Kyungsu Kang - https://github.com/kakasoo
*
* @template T Target type to resolve
*
* @evidence contracts/common.md#principled-implementation Conditional types unwrap boxed primitives, map callable values to never and recursively resolve public properties and array, tuple, Set and Map contents. Supported native classes pass through after the container branches; weak collections become never. Broad unknown/object inputs remain unchanged. TupleStack preserves a revisited tuple-rest identity rather than imposing a depth limit, and arrays bypass the Equal comparison to avoid eager recursive-alias evaluation.
* @evidence contracts/common.md#clear-and-simple-design A thin alias chooses between the original and the resolved form and delegates structure-specific work to ResolvedMain, ResolvedObject and ResolvedArray.
* @evidence contracts/common.md#prohibited-implementation-shortcuts It is a structural mapping over the type with no consumer names, casts or runtime code.
* @evidence contracts/common.md#meaningful-documentation The comment states what is resolved and which categories are preserved; recursion and tuple guards are explained in line comments at their private declarations.
*/
export type Resolved<T> = unknown extends T
? T
: object extends T
? T
: T extends readonly unknown[]
? ResolvedMain<T> // avoid eagerly comparing recursive tuple rest aliases
: Equal<T, ResolvedMain<T>> extends true
? T
: ResolvedMain<T>;
// TupleStack closes recursive tuple rest cycles without limiting other nesting.
type ResolvedMain<T, TupleStack = never> = 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, TupleStack>
: ValueOf<T>;
type ResolvedObject<T extends object, TupleStack> =
T extends Array<infer U>
? IsTupleLike<T> extends true
? T extends TupleStack
? T
: ResolvedArray<T, TupleStack | T>
: Array<ResolvedMain<U, TupleStack>>
: T extends ReadonlyArray<infer U>
? IsTupleLike<T> extends true
? T extends TupleStack
? T
: ResolvedArray<T, TupleStack | T>
: ReadonlyArray<ResolvedMain<U, TupleStack>>
: T extends Set<infer U>
? Set<ResolvedMain<U, TupleStack>>
: T extends Map<infer K, infer V>
? Map<ResolvedMain<K, TupleStack>, ResolvedMain<V, TupleStack>>
: T extends ReadonlyMap<infer K, infer V>
? ReadonlyMap<
ResolvedMain<K, TupleStack>,
ResolvedMain<V, TupleStack>
>
: T extends ReadonlySet<infer U>
? ReadonlySet<ResolvedMain<U, TupleStack>>
: T extends WeakSet<any> | WeakMap<any, any>
? never
: T extends NativeClass
? T
: {
[P in keyof T]: ResolvedMain<T[P], TupleStack>;
};
type ResolvedArray<T extends readonly unknown[], TupleStack> = {
[P in keyof T]: ResolvedMain<T[P], TupleStack>;
};The optional pick generator selects among lazy generation candidates for unions and alternatives. Return one of the supplied candidates; typia invokes only the selected candidate. The callback receives the generator object as its receiver. Omitting pick retains uniform built-in selection. This hook is independent of custom integer generation and does not control randomness inside format or pattern generators.
Tags in action
The constraints youโd normally use for runtime validation also pin down what random produces. Type tags and comment tags compile to the same code, so either style works:
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
import typia from "typia";
import * as _randomFormatDatetime_1 from "typia/lib/internal/_randomFormatDatetime";
import * as _randomInteger_1 from "typia/lib/internal/_randomInteger";
import * as _randomNumber_1 from "typia/lib/internal/_randomNumber";
import * as _randomPattern_1 from "typia/lib/internal/_randomPattern";
import * as _randomPick_1 from "typia/lib/internal/_randomPick";
import * as _randomString_1 from "typia/lib/internal/_randomString";
const data = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
type: (_generator?.integer ?? _randomInteger_1._randomInteger)({
type: "integer",
}),
number: (_generator?.pick ?? _randomPick_1._randomPick).call(_generator, [
() => undefined,
() =>
(_generator?.number ?? _randomNumber_1._randomNumber)({
type: "number",
exclusiveMinimum: 19,
maximum: 100,
}),
])(),
string: (_generator?.string ?? _randomString_1._randomString)({
type: "string",
minLength: 3,
}),
pattern: (_generator?.pattern ?? _randomPattern_1._randomPattern)(
new RegExp("^[a-z]+$"),
),
format: (_generator?.pick ?? _randomPick_1._randomPick).call(_generator, [
() => null,
() =>
(
_generator?.datetime ?? _randomFormatDatetime_1._randomFormatDatetime
)(),
])(),
});
let _generator;
return (generator_1) => {
_generator = generator_1;
return _ro0();
};
})()();
console.log(data);Type tags are the recommended form. They are statically checked by the TypeScript compiler (a misspelled format string is rejected at compile time), they compose with & and | like any other type, and they let you define custom constraints. Comment tags only exist for legacy JSDoc-style projects, and a typo there falls back to defaults silently โ for long-running test suites and especially anything that seeds a real database, prefer type tags. See Special Tags for the trade-off in full.
Custom tags
Defining a custom type tag for validation also gives you a hook for random generation. When you write validate on the tag, typia uses it for assert/is/validate โ and uses the tagโs kind to look up a generator on the runtime IRandomGenerator.
TypeScript Source
import typia from "typia";
import { _randomNumber } from "typia/lib/internal/_randomNumber";
import { _randomString } from "typia/lib/internal/_randomString";
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
import typia from "typia";
import * as _randomFormatUuid_1 from "typia/lib/internal/_randomFormatUuid";
import * as _randomNumber_1 from "typia/lib/internal/_randomNumber";
import { _randomNumber } from "typia/lib/internal/_randomNumber";
import * as _randomString_1 from "typia/lib/internal/_randomString";
import { _randomString } from "typia/lib/internal/_randomString";
const data = (() => {
const _ro0 = (_recursive = false, _depth = 0) => ({
id: (_generator?.uuid ?? _randomFormatUuid_1._randomFormatUuid)(),
dollar: (_generator?.string ?? _randomString_1._randomString)({
type: "string",
"x-typia-monetary": "dollar",
}),
postfix: (_generator?.string ?? _randomString_1._randomString)({
type: "string",
"x-typia-postfix": "abcd",
}),
powerOf: (_generator?.number ?? _randomNumber_1._randomNumber)({
type: "number",
"x-typia-powerOf": 2,
}),
});
let _generator;
return (generator_1) => {
_generator = generator_1;
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);A custom tag without a validate is fine for documentation purposes, but if you want random to actually produce values that satisfy it, define the validation logic. The same validate then doubles as the check used by typia.assert<T>.
Where to go next
- The full tag catalogue โ Special Tags
- Validating randomly-generated data round-trips โ
assert - Cloning / pruning random values โ Miscellaneous module