Class Parser<T>Abstract

The Parser class is an abstract base class designed to safely extract and validate values from various structured data sources (e.g., FormData, URLSearchParams, or JSON objects). It provides a set of methods to access the data in a type-safe manner, ensuring that required fields are present and correctly typed.

Developers can extend the Parser class to create custom parsers (e.g., FormParser, SearchParamsParser, ObjectParser) that are tailored to specific data sources. Each subclass defines methods for accessing and validating fields in a predictable and error-safe way.

The primary goal is to wrap incoming data in a structured format, allowing downstream consumers (like DTOs in a Data class) to retrieve specific values without directly accessing the raw data, reducing the risk of runtime errors.

  • The Parser operates on a generic value, which can be any structured data object.
  • Methods in subclasses are responsible for checking the existence and type of specific fields before returning their values.
  • If a required field is missing or of an invalid type, the parser throws appropriate errors (MissingKeyError, InvalidTypeError, etc.).

The Parser class provides several custom error types:

  • MissingKeyError: Thrown when a required key is not present in the data.
  • InvalidTypeError: Thrown when the type of a value does not match the expected type.
  • InvalidInstanceOfError: Thrown when a value is not an instance of the expected class.

These errors are intended to simplify debugging and ensure strict validation of incoming data, which is especially useful in scenarios like form submissions or query parameter parsing.

class MyParser extends Parser<SomeValue> {
public get<K extends keyof SomeValue>(key: string): SomeValue[K] {
if (!(key in this.value)) throw new Parser.MissingKeyError(key);
return this.value[key];
}
}

let parser = new MyParser(someValue);
parser.get("key"); // Ensure the key exists and return the value safely.

Type Parameters

  • T = unknown

    The type of the value that the parser is operating on.

Hierarchy (View Summary)

Constructors

Properties

Methods

Constructors

Properties

value: T

Methods