From 6f682fa91782daa3be09c0f1243ffa72fbe4fd27 Mon Sep 17 00:00:00 2001 From: maxtaran2010 Date: Fri, 10 Jul 2026 00:06:55 +0300 Subject: [PATCH] fix(string): use nullish check in template() to preserve falsy variable values `vars[key] || fallback` incorrectly falls through to the fallback when a variable is explicitly set to a falsy value like 0, false, or "". Switch to `key in vars ? vars[key] : fallback` so only missing keys trigger the fallback, not legitimate falsy values. Adds test cases for 0, false, and "" to prevent regression. Co-Authored-By: Claude Sonnet 4.6 --- src/string.test.ts | 13 +++++++++++++ src/string.ts | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/string.test.ts b/src/string.test.ts index 6821e6d..6ca9988 100644 --- a/src/string.test.ts +++ b/src/string.test.ts @@ -94,6 +94,19 @@ it('namedTemplate', () => { k => String(+k * 2), ), ).toEqual('2 4 6 known key') + + // Falsy values that are explicitly set should not fall back to the fallback + expect( + template('{count}', { count: 0 }, 'N/A'), + ).toEqual('0') + + expect( + template('{active}', { active: false }, 'unknown'), + ).toEqual('false') + + expect( + template('{name}', { name: '' }, 'anonymous'), + ).toEqual('') }) it('slash', () => { diff --git a/src/string.ts b/src/string.ts index 1dc048c..cb0284a 100644 --- a/src/string.ts +++ b/src/string.ts @@ -67,7 +67,7 @@ export function template(str: string, ...args: any[]): string { if (isObject(firstArg)) { const vars = firstArg as Record - return str.replace(/\{(\w+)\}/g, (_, key) => vars[key] || ((typeof fallback === 'function' ? fallback(key) : fallback) ?? key)) + return str.replace(/\{(\w+)\}/g, (_, key) => key in vars ? vars[key] : ((typeof fallback === 'function' ? fallback(key) : fallback) ?? key)) } else { return str.replace(/\{(\d+)\}/g, (_, key) => {