Skip to content

Tighten parseReviver context type to reflect ES2023 spec (source is only present for primitives) #10817

@jasonsaayman

Description

@jasonsaayman

Background

PR #10782 added the ES2023 context argument to the parseReviver type:

// index.d.ts:441 / index.d.cts:544
parseReviver?: (this: any, key: string, value: any, context?: { source: string }) => any;

This is correct as far as it goes, but it's slightly looser than the spec.

The gap

Per the TC39 proposal-json-parse-with-source, context.source is only set when the reviver is invoked on a primitive value (string, number, boolean, null). When the reviver is invoked on an object or array, source is absent from the context object.

The current typing says "if context is provided, source is always a string." That's true for primitives but not for object/array reviver invocations. A user can legally write:

parseReviver: (key, value, context) => {
  if (typeof value === 'object') {
    return context.source.length; // ← types say string, runtime undefined → crash
  }
}

Proposed fix

Mark source as optional:

parseReviver?: (this: any, key: string, value: any, context?: { source?: string }) => any;

Apply to both index.d.ts and index.d.cts.

Acceptance criteria

  • Update parseReviver signature in index.d.ts and index.d.cts to context?: { source?: string }
  • Add a tsd (or equivalent dtslint) test asserting:
    • The 4th argument is optional
    • context.source is typed as string | undefined, not string
    • The 3-arg form (no context) still type-checks for backward compatibility
  • Update the docs example in docs/pages/advanced/request-config.md if it relies on the looser typing (the existing examples already use context?.source which works either way)

Context

Patch-level change; types only.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions