mozilla/pdf.js · error · TypeError

Invalid field index: must be a number

Error message

Invalid field index: must be a number

What it means

Thrown by `Doc.getNthFieldName(nIndex)` (src/scripting_api/doc.js:1025). After unwrapping an optional `{nIndex}` object, it requires a numeric index. Returns the field name at that position or `null` if out of range — only the type mismatch throws, not an out-of-bounds index.

Source

Thrown at src/scripting_api/doc.js:1025

  getIcon() {
    /* Not implemented */
  }

  getLegalWarnings() {
    /* Not implemented */
  }

  getLinks() {
    /* Not implemented */
  }

  getNthFieldName(nIndex) {
    if (nIndex && typeof nIndex === "object") {
      nIndex = nIndex.nIndex;
    }
    if (typeof nIndex !== "number") {
      throw new TypeError("Invalid field index: must be a number");
    }
    if (0 <= nIndex && nIndex < this.numFields) {
      return this._fieldNames[Math.trunc(nIndex)];
    }
    return null;
  }

  getNthTemplate() {
    return null;
  }

  getOCGs() {
    /* Not implemented */
  }

  getOCGOrder() {
    /* Not implemented */
  }

View on GitHub (pinned to 5903d58d58)

Solutions

  1. Coerce to a number: `doc.getNthFieldName(Number(i))`.
  2. Validate the index is a finite number and within `[0, doc.numFields)` before calling.
  3. When passing an object, use the key `nIndex` (e.g. `{nIndex: 0}`).

Example fix

// before
for (let i = field.value; i < doc.numFields; i++) {
  console.println(doc.getNthFieldName(i)); // field.value is a string
}
// after
for (let i = Number(field.value); i < doc.numFields; i++) {
  console.println(doc.getNthFieldName(i));
}
Defensive patterns

Strategy: type-guard

Validate before calling

function getNthFieldNameSafe(doc, nIndex) {
  if (nIndex && typeof nIndex === 'object') nIndex = nIndex.nIndex;
  if (typeof nIndex !== 'number' || !Number.isFinite(nIndex)) return null;
  return doc.getNthFieldName(nIndex);
}

Type guard

function isFieldIndex(v) {
  if (v && typeof v === 'object') v = v.nIndex;
  return typeof v === 'number' && Number.isFinite(v);
}

Prevention

When it happens

Trigger: Calling `doc.getNthFieldName('0')` (string index), `doc.getNthFieldName()` (undefined), or `doc.getNthFieldName(fieldRef)` passing a field object instead of an integer. Iterating with a string counter from a parsed form value.

Common situations: Loops where the counter is read from a form field value (always a string in the Acrobat API) and not coerced; passing an object whose key is not `nIndex`; UI code that threads a 1-based display index straight through.

Related errors


AI-assisted analysis of mozilla/pdf.js@5903d58d58 (2026-08-13). Data as JSON: /api/errors/8d4597b2b4bbe4e2. Report an issue: GitHub.