String Template Interpolation With Missing Key Errors

Render double-brace placeholders from a plain object, raising clear errors for missing keys instead of silently printing undefined.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
export function interpolate(template, values) {
  if (typeof template !== "string") throw new TypeError("template must be a string");
  if (values === null || typeof values !== "object") {
    throw new TypeError("values must be an object");
  }
  return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (match, key) => {
    if (!Object.prototype.hasOwnProperty.call(values, key)) {
      throw new RangeError('missing value for "' + key + '"');
    }
    const value = values[key];
    if (value === null || value === undefined) {
      throw new TypeError('nullish value for "' + key + '"');
    }
    return String(value);
  });
}

How the snippet works

String Template Interpolation With Missing Key Errors keeps everything in the function interpolate.

Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.

What to watch for

  • The guard typeof template !== "string" short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: export function interpolate(template, values)

interpolate is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

if (typeof template !== "string") throw new TypeError("template must be a string");
throw new RangeError('missing value for "' + key + '"');
throw new TypeError('nullish value for "' + key + '"');

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
It throws `TypeError` and `RangeError` before any real work runs, via the guard `typeof template !== "string"` — handle it at the call site or let it propagate deliberately.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `interpolate` at load time.