ianstormtaylor/slate · error · Error

Expected index to be a number

Error message

Expected index to be a number

What it means

Node.child(root, index) requires the index to be a number; passing anything else (undefined, a string, null) throws this error. It is a defensive type check for a JavaScript API that would otherwise silently return undefined.

Source

Thrown at packages/slate/src/interfaces/node.ts:277

    path: Path,
    options: NodeAncestorsOptions = {}
  ): Generator<NodeEntry<Ancestor>, void, undefined> {
    for (const p of Path.ancestors(path, options)) {
      const n = Node.ancestor(root, p)
      const entry: NodeEntry<Ancestor> = [n, p]
      yield entry
    }
  },

  child(root: Node, index: number): Descendant {
    if (Node.isText(root)) {
      throw new Error(
        `Cannot get the child of a text node: ${Scrubber.stringify(root)}`
      )
    }

    if (typeof index !== 'number') {
      throw new Error('Expected index to be a number')
    }

    const c = root.children[index] as Descendant

    if (c == null) {
      throw new Error(
        `Cannot get child at index \`${index}\` in node: ${Scrubber.stringify(
          root
        )}`
      )
    }

    return c
  },

  *children(
    root: Node,
    path: Path,

View on GitHub (pinned to 72a37c701e)

Solutions

  1. Check the index is a number before calling (Number.isInteger guard)
  2. Fix the call site — the argument is likely undefined due to a missing/destructured variable
  3. If indices come from external data, validate/coerce with Number() and reject NaN

Example fix

// before
const c = Node.child(node, idx) // idx is undefined

// after
const c =
  typeof idx === 'number' ? Node.child(node, idx) : null
Defensive patterns

Strategy: type-guard

Validate before calling

if (Number.isInteger(index)) {
  const c = Node.child(node, index)
}

Type guard

const isValidIndex = (i) => Number.isInteger(i)

Prevention

When it happens

Trigger: Calling Node.child(node, undefined) — commonly a destructuring or argument-count mistake; passing a string index from URL params or parsed JSON; calling child with a missing second argument.

Common situations: Refactors that drop or reorder the index argument; index variables shadowed/undefined; data-driven traversal where indices come from untyped sources.

Understand the failure class

Background: Invalid argument type errors: "must be of type string", "expected X, got Y", and ERR_INVALID_ARG_TYPE explained — this error's family across 15 libraries.

Related errors


AI-assisted analysis of ianstormtaylor/slate@72a37c701e (2026-08-27). Data as JSON: /api/errors/6eca571921fe7238. Report an issue: GitHub.