Skip to content

JSONParsed

reference
1 min readUpdated

Kind: Type

Source: src/utils/types.ts

Part of: Utils

Convert a type to a JSON-compatible type.

Non-JSON values such as Date implement .toJSON(), so they can be transformed to a value assignable to JSONObject

JSON.stringify() throws a TypeError when it encounters a bigint value, unless a custom replacer function or .toJSON() method is provided.

This behaviour can be controlled by the TError generic type parameter, which defaults to bigint | ReadonlyArray<bigint>. You can set it to never to disable this check.

JSONParsed<T> maps a TypeScript type to the shape produced by JSON serialization. Values with a .toJSON() method, such as Date, are converted through that method, while bigint values are rejected by default because JSON.stringify() throws for them.

Definition

ts
T extends { toJSON(): infer J } ? (() => J) extends () => JSONPrimitive ? J : (() => J) extends () => { toJSON(): unknown } ? {} : JSONParsed<J, TError> : T extends JSONPrimitive ? T : T extends InvalidJSONValue ? never : T extends ReadonlyArray<unknown> ? { [K in keyof T]: JSONParsed<InvalidToNull<T[K]>, TError> } extends infer A ? A extends ReadonlyArray<unknown> ? A : JSONParsed<InvalidToNull<T[number]>, TError>[] : never : T extends Set<unknown> | Map<unknown, unknown> | Record<string, never> ? {} : T extends object ? T[keyof T] extends TError ? never : { [K in keyof OmitSymbolKeys<T> as IsInvalid<T[K]> extends true ? never : K]: boolean extends IsInvalid<T[K]> ? JSONParsed<T[K], TError> | undefined : JSONParsed<T[K], TError> } : T extends unknown ? T extends TError ? never : JSONValue : never

Diagram

mermaid
graph LR
  T[Input type T] --> P[JSONParsed<T>]
  P --> J[JSON-compatible type]
  D[Date or value with toJSON()] --> J
  B[bigint value] --> E[TError check]
  E -->|default| R[Rejected]
  E -->|TError = never| J

Usage

ts
import type { JSONParsed } from "./utils/types";

type Input = {
  createdAt: Date;
  tags: readonly string[];
};

type SerializedInput = JSONParsed<Input>;

const value: SerializedInput = {
  createdAt: new Date().toJSON(),
  tags: ["release"],
};

declare const source: { total: bigint };

// bigint is checked by default.
type CheckedValue = JSONParsed<typeof source>;

// Disable the bigint check when serialization is handled separately.
type AllowedValue = JSONParsed<typeof source, never>;

AI Coding Instructions

  • Use JSONParsed<T> for types representing data after JSON serialization.
  • Expect values with .toJSON() methods to resolve to their JSON return type.
  • Keep the default TError setting when bigint values should be rejected.
  • Set TError to never only when bigint serialization is handled with a replacer or custom .toJSON() method.

Was this page helpful?

Download as PDF
JSONParsed — Hono (narrator proof)