R
fn

templateObject

v0.0.4tested

Replace `{path}` placeholders in a template string with values resolved from `args` by dot-path. Placeholder keys are inferred from the template, so `args` is type-checked and auto-completed against them.

Example

ts
templateObject('Hello, {name}!', { name: 'John' }); // 'Hello, John!'
templateObject('Hi {user.addresses.0.city}', { user: { addresses: [{ city: 'NY' }] } }); // 'Hi NY'
templateObject('Hello, {name}!', {}, 'Guest'); // 'Hello, Guest!'
templateObject('Hello, {name}!', {}, key => `<${key}>`); // 'Hello, <name>!'

Signature

ts
export function templateObject<
  T extends string,
  A extends GenerateTypes<ExtractPlaceholders<T>, TemplateValue> & Collection,
>(template: T, args: A, fallback?: TemplateFallback): string{ ... }

Type Parameters

Textends string
Aextends GenerateTypes<ExtractPlaceholders<T>, TemplateValue> & Collection

Parameters

ParameterTypeDescription
templateTTemplate string with `{path}` placeholders
argsASource values, keyed by the placeholder paths
fallback?TemplateFallback | undefinedValue (or factory) used when a placeholder cannot be resolved; defaults to an empty string

Returns

stringThe interpolated string