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) => {