jquense/yup · error · TypeError

ref must be a string, got:

Error message

ref must be a string, got: 

What it means

Reference (created via yup.ref()) models a pointer to another field and requires its key to be a string, since the key is trimmed and parsed for `$`/`this` prefixes. Passing a non-string (number, object, undefined) means the reference path cannot be built, so the constructor throws this TypeError including the offending value. It fails fast at ref creation, before any validation.

Source

Thrown at src/Reference.ts:34

) {
  return new Reference<TValue>(key, options);
}

export default class Reference<TValue = unknown> {
  readonly key: string;
  readonly isContext: boolean;
  readonly isValue: boolean;
  readonly isSibling: boolean;
  readonly path: any;

  readonly getter: (data: unknown) => unknown;
  readonly map?: (value: unknown) => TValue;

  declare readonly __isYupRef: boolean;

  constructor(key: string, options: ReferenceOptions<TValue> = {}) {
    if (typeof key !== 'string')
      throw new TypeError('ref must be a string, got: ' + key);

    this.key = key.trim();

    if (key === '') throw new TypeError('ref must be a non-empty string');

    this.isContext = this.key[0] === prefixes.context;
    this.isValue = this.key[0] === prefixes.value;
    this.isSibling = !this.isContext && !this.isValue;

    let prefix = this.isContext
      ? prefixes.context
      : this.isValue
      ? prefixes.value
      : '';

    this.path = this.key.slice(prefix.length);
    this.getter = this.path && getter(this.path, true);
    this.map = options.map;

View on GitHub (pinned to ff31eee8a2)

Solutions

  1. Pass a string to yup.ref(): convert numbers with String(i) or template literals.
  2. Guard the variable before calling: ensure it is defined and a string.
  3. If the path is built dynamically, coerce/join parts: yup.ref([a, b].join('.')).

Example fix

// before
yup.ref(index)
// after
yup.ref(String(index))
Defensive patterns

Strategy: type-guard

Validate before calling

const makeRef = (key) => {
  if (typeof key !== 'string') throw new TypeError(`ref key must be a string, got: ${typeof key}`);
  return yup.ref(key);
};

Type guard

const isRefKey = (v) => typeof v === 'string';

Prevention

When it happens

Trigger: yup.ref(42), yup.ref(someVariable) where the variable is undefined/null/number, or programmatic ref paths built from non-string data (e.g. JSON config numbers).

Common situations: Dynamic field paths from numeric indices (`ref(i)` instead of `` ref(`${i}`) ``); destructured options with undefined path; reading paths from query params or env without coercion to string.

Related errors


AI-assisted analysis of jquense/yup@ff31eee8a2 (2026-08-31). Data as JSON: /api/errors/61858463aaaf3a46. Report an issue: GitHub.