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

snippet
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);
  });
}