@illavv/run_typer - v3.2.3
    Preparing search index...

    Class Typer

    Class representing a type checker. Version: 3.2.3

    3.2.3

    Index

    Constructors

    Methods

    • Validates and returns an array

      Type Parameters

      • T = unknown

        The expected element type

      Parameters

      • value: unknown

        The value to validate

      Returns T[]

      The validated array

      If not an array

    • Validates and returns a boolean

      Parameters

      • value: unknown

        The value to validate

      Returns boolean

      The validated boolean

      If not a boolean

    • Validates and returns a number

      Parameters

      • value: unknown

        The value to validate

      Returns number

      The validated number

      If not a number

    • Validates and returns an object

      Type Parameters

      • T extends Record<string, unknown> = Record<string, unknown>

        The expected object type

      Parameters

      • value: unknown

        The value to validate

      Returns T

      The validated object

      If not an object

    • Assert that a value is of a specific type. Logs a warning if incorrect.

      Parameters

      • value: unknown

        The value to check.

      • expectedType: string | string[]

        The expected type(s).

      Returns void

      Typer.assert(42, "number"); // No output
      Typer.assert("hello", "number"); // Warning in console
    • Validates and returns a string

      Parameters

      • value: unknown

        The value to validate

      Returns string

      The validated string

      If not a string

    • Recursively validates an object against a nested schema.

      Parameters

      • schema: Record<string, unknown>

        The expected structure definition.

      • obj: Record<string, unknown>

        The object to validate.

      • path: string = ''

        The current path for error reporting (internal use).

      • strictMode: boolean = false

        Whether to reject extra keys not in schema.

      Returns StructureValidationReturn

      • Validation result with errors array.
      const schema = {
      name: "string",
      age: "number",
      hobbies: ["string"],
      address: {
      street: "string",
      city: "string?"
      }
      };
      const obj = { name: "John", age: 25, hobbies: ["reading"] };
      console.log(Typer.checkStructure(schema, obj)); // { isValid: true, errors: [] }
    • Expects a function to conform to specified input and output types.

      Parameters

      • funct: Function

        The function to type-check.

      • types: TyperExpectTypes

        The expected types for the function's parameters and return value.

        Defines the expected input and output types for a function.

        • paramTypes: string[]

          The expected type(s) of the function's parameters

        • returnType: string[]

          The expected return type(s) of the function

      Returns (...args: unknown[]) => any

      A new function that type-checks its arguments and return value.

      If the types object does not contain exactly 3 keys or the required type properties.

      If the function or types object does not conform to the expected types.

      const typedFunction = Typer.expect(
      (x: number) => x * 2,
      { paramTypes: ["number"], returnType: ["number"] }
      );
      console.log(typedFunction(3)); // 6
    • Exports all registered types as a JSON string.

      Returns string

      The serialized types.

      console.log(Typer.exportTypes()); // '["array","number","string","boolean"]'
      
    • Imports types from a JSON string.

      Parameters

      • json: string

        The JSON string containing type names.

      Returns void

      Typer.importTypes('["customType"]');
      
    • Checks if the provided value matches one or more specified types.

      Overloads:

      • When called with a known built-in alias, the type guard is automatically inferred from TypeMap (e.g. "number" narrows to number).
      • For custom registered types, an explicit generic T may be supplied.

      Type Parameters

      Parameters

      • value: unknown

        The value to check.

      • types: K | readonly K[]

        One or more types to check against.

      Returns value is TypeMap[K]

      Returns true if the value matches any type, false otherwise.

      if (typer.is(value, "string")) {
      // value is now narrowed to string by the type guard
      console.log(value.toUpperCase());
      }
      typer.is(42, "number"); // true
      typer.is("hello", ["string", "number"]); // true
      typer.is<MyShape>(payload, "my_custom_type"); // explicit generic for custom types
    • Checks if the provided value matches one or more specified types.

      Overloads:

      • When called with a known built-in alias, the type guard is automatically inferred from TypeMap (e.g. "number" narrows to number).
      • For custom registered types, an explicit generic T may be supplied.

      Type Parameters

      • T = unknown

        The expected type for better TypeScript inference

      Parameters

      • value: unknown

        The value to check.

      • types: string | readonly string[]

        One or more types to check against.

      Returns value is T

      Returns true if the value matches any type, false otherwise.

      if (typer.is(value, "string")) {
      // value is now narrowed to string by the type guard
      console.log(value.toUpperCase());
      }
      typer.is(42, "number"); // true
      typer.is("hello", ["string", "number"]); // true
      typer.is<MyShape>(payload, "my_custom_type"); // explicit generic for custom types
    • Type-safe array validation

      Type Parameters

      • T = unknown

        The expected element type

      Parameters

      • value: unknown

        The value to check

      Returns value is T[]

      Type guard for array

    • Checks if the provided parameter is an array of a specified type.

      Type Parameters

      • T = unknown

        The expected element type

      Parameters

      • elementType: string

        The type of elements that the array should contain.

      • p: unknown

        The parameter to check.

      Returns T[]

      Typed array of elements

      Throws if the parameter is not an array of the specified type.

      const numbers = typer.isArrayOf<number>("number", [1, 2, 3]); // numbers: number[]
      const strings = typer.isArrayOf<string>("string", ["a", "b"]); // strings: string[]
    • Checks that the parameter is a syntactically valid Base64 string. Supports both standard and URL-safe variants. Padding is required when requirePadding is true (default).

      Parameters

      • p: unknown

        The parameter to check

      • Optionalopts: { requirePadding?: boolean; urlSafe?: boolean } = {}

        Options

      Returns string

      The validated Base64 string

      If p is not a valid Base64 string

    • Type-safe boolean validation

      Parameters

      • value: unknown

        The value to check

      Returns value is boolean

      Type guard for boolean

    • Checks if the provided parameter is a valid email address.

      Parameters

      • p: unknown

        The parameter to check.

      Returns string

      The validated email string

      Throws if the parameter is not a valid email address.

      const email = typer.isEmail("test@example.com"); // email: string
      
    • Checks that the parameter is "empty": empty string (after trim), empty array, empty Map/Set, or object with no own enumerable keys.

      Parameters

      • p: unknown

        The parameter to check

      Returns unknown

      The validated empty value

      If p is not empty or not a supported container

    • Checks that the parameter is a finite number (rejects NaN and Infinity). Stricter than isType("number", x), which accepts NaN for compatibility with typeof x === "number".

      Parameters

      • p: unknown

        The parameter to check

      Returns number

      The validated finite number

      If p is not a finite number

    • Checks that the parameter is a valid CSS hex color (#RGB, #RGBA, #RRGGBB, or #RRGGBBAA).

      Parameters

      • p: unknown

        The parameter to check

      Returns string

      The validated hex color

      If p is not a valid hex color

    • Checks if the provided parameter is a number within a specified range.

      Parameters

      • min: number

        The minimum value.

      • max: number

        The maximum value.

      • p: unknown

        The parameter to check.

      Returns number

      The validated number

      Throws if the parameter is not a number within the specified range.

      const age = typer.isInRange(18, 65, 25); // age: number
      
    • Checks that the parameter is an instance of the given constructor. Type-safe alternative to writing value instanceof MyClass everywhere.

      Type Parameters

      • T

        The instance type produced by the constructor

      Parameters

      • ctor: new (...args: never[]) => T

        The constructor to check against

      • p: unknown

        The parameter to check

      Returns T

      The validated instance

      If p is not an instance of ctor

    • Checks if the provided parameter is an integer.

      Parameters

      • p: unknown

        The parameter to check.

      Returns number

      The validated integer

      Throws if the parameter is not an integer.

      const count = typer.isInteger(42); // count: number
      
    • Checks that the parameter is a valid IPv4 address (dotted-quad notation).

      Parameters

      • p: unknown

        The parameter to check

      Returns string

      The validated IPv4 address

      If p is not a valid IPv4 address

    • Checks that the parameter is a valid IPv6 address. Uses the URL constructor as a permissive parser: any string accepted as the host portion of http://[<addr>]/ is considered valid.

      Parameters

      • p: unknown

        The parameter to check

      Returns string

      The validated IPv6 address

      If p is not a valid IPv6 address

    • Checks that the parameter is a valid ISO 8601 date string and returns the parsed Date. Accepts the formats produced by Date#toISOString plus reasonable variants (e.g. with timezone offsets).

      Parameters

      • p: unknown

        The parameter to check

      Returns Date

      The parsed date (always valid)

      If p is not a valid ISO 8601 date string

    • Checks that the length of a string or array falls within the given bounds.

      Type Parameters

      • T extends string | readonly unknown[]

        Either string or an array type

      Parameters

      • bounds: { max?: number; min?: number }

        Inclusive length bounds

      • p: unknown

        The parameter to check (string or array)

      Returns T

      The validated value

      If p is not a string/array or its length is out of range

    • Checks if the provided parameter is a negative integer.

      Parameters

      • p: unknown

        The parameter to check.

      Returns number

      The validated negative integer

      Throws if the parameter is not a negative integer.

      const count = typer.isNegativeInteger(-42); // count: number
      
    • Checks if the provided parameter is a negative number.

      Parameters

      • p: unknown

        The parameter to check.

      Returns number

      The validated negative number

      Throws if the parameter is not a negative number.

      const value = typer.isNegativeNumber(-10); // value: number
      
    • Inverse of isEmpty: checks the parameter is a non-empty string, array, Map, Set, or object.

      Type Parameters

      • T = unknown

        Caller-supplied container type for narrower inference

      Parameters

      • p: unknown

        The parameter to check

      Returns T

      The validated non-empty value

      If p is empty or not a supported container

    • Checks if the provided parameter is a non-empty array.

      Type Parameters

      • T = unknown

        The expected element type

      Parameters

      • p: unknown

        The parameter to check.

      Returns T[]

      The validated non-empty array

      Throws if the parameter is not a non-empty array.

      const items = typer.isNonEmptyArray<string>(["a", "b"]); // items: string[]
      
    • Checks if the provided parameter is a non-empty string.

      Parameters

      • p: unknown

        The parameter to check.

      Returns string

      The validated non-empty string

      Throws if the parameter is not a non-empty string.

      const name = typer.isNonEmptyString("Hello"); // name: string
      
    • Type-safe number validation

      Parameters

      • value: unknown

        The value to check

      Returns value is number

      Type guard for number

    • Type-safe object validation

      Type Parameters

      • T extends Record<string, unknown> = Record<string, unknown>

        The expected object type

      Parameters

      • value: unknown

        The value to check

      Returns value is T

      Type guard for object

    • Checks if the provided parameter is one of the specified values.

      Type Parameters

      • T

        The expected type of the values

      Parameters

      • values: readonly T[]

        The values to check against.

      • p: unknown

        The parameter to check.

      Returns T

      The validated value

      Throws if the parameter is not one of the specified values.

      const color = typer.isOneOf(["red", "blue", "green"] as const, "blue"); // color: "red" | "blue" | "green"
      
    • Checks if the provided parameter is a valid phone number.

      Parameters

      • p: unknown

        The parameter to check.

      Returns string

      The validated phone number string

      Throws if the parameter is not a valid phone number.

      const phone = typer.isPhoneNumber("+1234567890"); // phone: string
      const phone2 = typer.isPhoneNumber("(555) 123-4567"); // phone2: string
    • Checks that the parameter is a plain object (object literal or Object.create(null)). Rejects class instances, arrays, dates, maps, etc.

      Type Parameters

      • T extends Record<string, unknown> = Record<string, unknown>

        The expected plain object shape

      Parameters

      • p: unknown

        The parameter to check

      Returns T

      The validated plain object

      If p is not a plain object

    • Checks if the provided parameter is a positive integer.

      Parameters

      • p: unknown

        The parameter to check.

      Returns number

      The validated positive integer

      Throws if the parameter is not a positive integer.

      const count = typer.isPositiveInteger(42); // count: number
      
    • Checks if the provided parameter is a positive number.

      Parameters

      • p: unknown

        The parameter to check.

      Returns number

      The validated positive number

      Throws if the parameter is not a positive number.

      const value = typer.isPositiveNumber(10); // value: number
      
    • Checks that the parameter is a Promise (or a thenable).

      Type Parameters

      • T = unknown

        The resolved promise type (caller-supplied)

      Parameters

      • p: unknown

        The parameter to check

      Returns Promise<T>

      The validated promise

      If p is not a Promise/thenable

    • Checks that the parameter is a safe integer (within Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER).

      Parameters

      • p: unknown

        The parameter to check

      Returns number

      The validated safe integer

      If p is not a safe integer

    • Type-safe string validation

      Parameters

      • value: unknown

        The value to check

      Returns value is string

      Type guard for string

    • Check if the parameter matches one of the specified types.

      Overloads:

      • When called with a known built-in type alias (or array of aliases), the return type is inferred from TypeMap (e.g. "string"string).
      • Otherwise the caller can supply an explicit generic T, which falls back to unknown.

      Type Parameters

      Parameters

      • types: K | readonly K[]

        The types to check against.

      • p: unknown

        The parameter to check.

      Returns TypeMap[K]

      Returns the value cast to the expected type

      Throws if the parameter does not match any of the specified types.

      const value = typer.isType("string", "Hello"); // value is typed as string (no generic needed)
      const arr = typer.isType(["number", "boolean"], 42); // typed as number | boolean
      typer.isType<MyShape>("my_custom_type", payload); // explicit generic for custom types
    • Check if the parameter matches one of the specified types.

      Overloads:

      • When called with a known built-in type alias (or array of aliases), the return type is inferred from TypeMap (e.g. "string"string).
      • Otherwise the caller can supply an explicit generic T, which falls back to unknown.

      Type Parameters

      • T = unknown

        The expected type for better TypeScript inference

      Parameters

      • types: string | readonly string[]

        The types to check against.

      • p: unknown

        The parameter to check.

      Returns T

      Returns the value cast to the expected type

      Throws if the parameter does not match any of the specified types.

      const value = typer.isType("string", "Hello"); // value is typed as string (no generic needed)
      const arr = typer.isType(["number", "boolean"], 42); // typed as number | boolean
      typer.isType<MyShape>("my_custom_type", payload); // explicit generic for custom types
    • Checks if the provided parameter is a valid URL.

      Parameters

      • p: unknown

        The parameter to check.

      Returns string

      Throws if the parameter is not a valid URL.

      console.log(Typer.isURL("https://example.com")); // true
      console.log(Typer.isURL("invalid-url")); // false
    • Checks that the parameter is a valid UUID (versions 1-5, RFC 4122).

      Parameters

      • p: unknown

        The parameter to check

      Returns string

      The validated UUID

      If p is not a valid UUID

    • Get all registered types.

      Returns string[]

      An array of registered type names.

      console.log(Typer.listTypes()); // ["array", "number", "string", "boolean"]
      
    • Checks that the parameter is a string matching the given regular expression.

      Parameters

      • regex: RegExp

        The pattern to match against

      • p: unknown

        The parameter to check

      Returns string

      The validated string

      If p is not a string or does not match

    • Wraps an existing validator so that null is also accepted and returned as-is. Useful as a building block for nullable schema fields.

      Type Parameters

      • T

        The type produced by the underlying validator on success

      Parameters

      • validator: Validator<T>

        The validator to make nullable

      Returns Validator<T | null>

      A new validator that accepts T or null

      const maybeStr = typer.nullable(v => typer.asString(v));
      maybeStr(null); // null
      maybeStr("hi"); // "hi"
    • Wraps an existing validator so that undefined is also accepted. Useful for optional schema fields.

      Type Parameters

      • T

        The type produced by the underlying validator on success

      Parameters

      • validator: Validator<T>

        The validator to make optional

      Returns Validator<T | undefined>

      A new validator that accepts T or undefined

      const maybeNum = typer.optional(v => typer.asNumber(v));
      maybeNum(undefined); // undefined
      maybeNum(42); // 42
    • Universal "parse" entry point. Validates value against either:

      • a built-in type alias ("string", "number", ...),
      • an array of aliases (["string", "number"] → union),
      • a Validator<T> function,
      • or a Schema object.

      Returns the value typed correctly. Throws a TypeError on failure.

      No as const is needed when calling with a literal schema thanks to the <const S> parameter — the inferred type matches the schema.

      Type Parameters

      Parameters

      • types: K | readonly K[]
      • value: unknown

      Returns TypeMap[K]

      const user = typer.parse(
      { id: 'number', name: 'string', email: 'string?' },
      payload,
      );
      // user is typed as { id: number; name: string; email?: string | null }
    • Universal "parse" entry point. Validates value against either:

      • a built-in type alias ("string", "number", ...),
      • an array of aliases (["string", "number"] → union),
      • a Validator<T> function,
      • or a Schema object.

      Returns the value typed correctly. Throws a TypeError on failure.

      No as const is needed when calling with a literal schema thanks to the <const S> parameter — the inferred type matches the schema.

      Type Parameters

      • T

      Parameters

      Returns T

      const user = typer.parse(
      { id: 'number', name: 'string', email: 'string?' },
      payload,
      );
      // user is typed as { id: number; name: string; email?: string | null }
    • Universal "parse" entry point. Validates value against either:

      • a built-in type alias ("string", "number", ...),
      • an array of aliases (["string", "number"] → union),
      • a Validator<T> function,
      • or a Schema object.

      Returns the value typed correctly. Throws a TypeError on failure.

      No as const is needed when calling with a literal schema thanks to the <const S> parameter — the inferred type matches the schema.

      Type Parameters

      Parameters

      • schema: S
      • value: unknown

      Returns {
          [K in string | number | symbol]: (
              { [K in string
              | number
              | symbol]: ResolveSchemaValue<S[K]> } & {
                  [K in string | number | symbol]?: ResolveSchemaValue<S[K]>
              }
          )[K]
      }

      const user = typer.parse(
      { id: 'number', name: 'string', email: 'string?' },
      payload,
      );
      // user is typed as { id: number; name: string; email?: string | null }
    • Universal "parse" entry point. Validates value against either:

      • a built-in type alias ("string", "number", ...),
      • an array of aliases (["string", "number"] → union),
      • a Validator<T> function,
      • or a Schema object.

      Returns the value typed correctly. Throws a TypeError on failure.

      No as const is needed when calling with a literal schema thanks to the <const S> parameter — the inferred type matches the schema.

      Type Parameters

      • T

      Parameters

      • types: string | readonly string[]
      • value: unknown

      Returns T

      const user = typer.parse(
      { id: 'number', name: 'string', email: 'string?' },
      payload,
      );
      // user is typed as { id: number; name: string; email?: string | null }
    • Register a new type in the typesMap.

      Type Parameters

      • T = unknown

        The input type that the validator expects

      • R = T

        The return type that the validator produces

      Parameters

      • name: string

        The name of the new type.

      • validator: (value: T) => R

        The function to validate the type.

      • override: boolean = false

        Whether to override the original configuration

      Returns void

      If the type name is already registered.

      // Register a positive number validator
      typer.registerType<unknown, number>("positive", (value) => {
      if (typeof value !== "number" || value <= 0) throw new TypeError("Must be positive");
      return value;
      });

      // Register a string length validator
      typer.registerType<unknown, string>("longString", (value) => {
      if (typeof value !== "string" || value.length < 10) throw new TypeError("Must be long string");
      return value;
      });
    • Validates value without throwing. Same input shapes as parse. Returns a discriminated union: { success: true, data } or { success: false, error }.

      Type Parameters

      Parameters

      • types: K | readonly K[]
      • value: unknown

      Returns ParseResult<TypeMap[K]>

      const result = typer.safeParse(
      { id: 'number', name: 'string' },
      payload,
      );
      if (result.success) {
      // result.data is { id: number; name: string }
      } else {
      console.error(result.error.message);
      }
    • Validates value without throwing. Same input shapes as parse. Returns a discriminated union: { success: true, data } or { success: false, error }.

      Type Parameters

      • T

      Parameters

      Returns ParseResult<T>

      const result = typer.safeParse(
      { id: 'number', name: 'string' },
      payload,
      );
      if (result.success) {
      // result.data is { id: number; name: string }
      } else {
      console.error(result.error.message);
      }
    • Validates value without throwing. Same input shapes as parse. Returns a discriminated union: { success: true, data } or { success: false, error }.

      Type Parameters

      Parameters

      • schema: S
      • value: unknown

      Returns ParseResult<
          {
              [K in string
              | number
              | symbol]: (
                  { [K in string
                  | number
                  | symbol]: ResolveSchemaValue<S[K]> } & {
                      [K in string | number | symbol]?: ResolveSchemaValue<S[K]>
                  }
              )[K]
          },
      >

      const result = typer.safeParse(
      { id: 'number', name: 'string' },
      payload,
      );
      if (result.success) {
      // result.data is { id: number; name: string }
      } else {
      console.error(result.error.message);
      }
    • Validates value without throwing. Same input shapes as parse. Returns a discriminated union: { success: true, data } or { success: false, error }.

      Type Parameters

      • T

      Parameters

      • types: string | readonly string[]
      • value: unknown

      Returns ParseResult<T>

      const result = typer.safeParse(
      { id: 'number', name: 'string' },
      payload,
      );
      if (result.success) {
      // result.data is { id: number; name: string }
      } else {
      console.error(result.error.message);
      }
    • Identity helper that preserves literal types of a schema declared as a variable. Use it when you want to declare the schema once, derive Infer<typeof schema>, and then call parse(schema, value) with full type inference — without sprinkling as const.

      Type Parameters

      Parameters

      • definition: S

      Returns S

      const userSchema = typer.schema({
      id: 'number',
      name: 'string',
      email: 'string?',
      });
      type User = Infer<typeof userSchema>;
      const user = typer.parse(userSchema, payload); // typed
    • Combines multiple validators into one that succeeds if any of them succeeds. The first matching validator's result is returned.

      Type Parameters

      • T extends readonly unknown[]

        Tuple of types produced by each validator

      Parameters

      • ...validators: { [K in string | number | symbol]: Validator<T[K]> }

        Validators to try in order

      Returns Validator<T[number]>

      A new validator that returns the first matching result

      If none of the validators accepts the value

      const stringOrNumber = typer.union(
      v => typer.asString(v),
      v => typer.asNumber(v),
      );
      stringOrNumber(42); // 42
      stringOrNumber("hi"); // "hi"
    • Unregister a type from the typesMap.

      Parameters

      • name: string

        The name of the type to remove.

      Returns void

      If the type does not exist.

      Typer.unregisterType("positive");
      
    • Validates an object against a schema.

      Parameters

      • schema: Record<string, string | string[]>

        The expected types for each key.

      • obj: Record<string, unknown>

        The object to validate.

      Returns string[]

      • An array of validation errors, or an empty array if valid.
      const schema = { name: "string", age: "number" };
      const obj = { name: "John", age: "25" };
      console.log(Typer.validate(schema, obj)); // ["Expected 'age' to be of type number, got string"]