Hyperlinkv0.8.0-beta.28

SchemaAST

SchemaAST.Literalclasseffect/SchemaAST.ts:1243
Literal

AST node matching an exact primitive value (string, number, boolean, or bigint).

Details

Parsing succeeds only when the input is strictly equal (===) to the stored literal. Numeric literals must be finite — Infinity, -Infinity, and NaN are rejected at construction time.

Example (Creating a literal AST)

import { SchemaAST } from "effect"

const ast = new SchemaAST.Literal("active")
console.log(ast.literal) // "active"
export class Literal extends Base {
  readonly _tag = "Literal"
  readonly literal: LiteralValue

  constructor(
    literal: LiteralValue,
    annotations?: Schema.Annotations.Annotations,
    checks?: Checks,
    encoding?: Encoding,
    context?: Context
  ) {
    super(annotations, checks, encoding, context)
    if (typeof literal === "number" && !globalThis.Number.isFinite(literal)) {
      throw new Error(`A numeric literal must be finite, got ${format(literal)}`)
    }
    this.literal = literal
  }
  /** @internal */
  getParser() {
    return fromConst(this, this.literal)
  }
  /** @internal */
  matchPart(s: string, _options: ParseOptions): LiteralValue | undefined {
    return s === globalThis.String(this.literal) ? this.literal : undefined
  }
  /** @internal */
  toCodecJson(): AST {
    return typeof this.literal === "bigint" ? literalToString(this) : this
  }
  /** @internal */
  toCodecStringTree(): AST {
    return typeof this.literal === "string" ? this : literalToString(this)
  }
  /** @internal */
  getExpected(): string {
    return typeof this.literal === "string" ? JSON.stringify(this.literal) : globalThis.String(this.literal)
  }
}
Referenced by 5 symbols