Call Signatures Type Callable Objects

Type a callable object with a call signature plus a property, build it with Object.assign, and call it through the interface.

TypescriptData Integrity

Code

typescriptsnippet
23 lines
// A call signature describes a value that can be invoked like a function.
interface PriceFormatter {
  (amount: number): string;
  currency: string;
}

function makeFormatter(currency: string): PriceFormatter {
  const format = (amount: number): string =>
    new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      minimumFractionDigits: 2,
    }).format(amount);

  return Object.assign(format, { currency });
}

const usd = makeFormatter('USD');
const eur = makeFormatter('EUR');

console.log(usd(19.5));
console.log(eur(19.5));
console.log('currencies:', usd.currency, eur.currency);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

$19.50
€19.50
currencies: USD EUR

Inside the snippet

Call Signatures Type Callable Objects keeps everything in the functions format and makeFormatter.

Using it

The primary signature is const format = (amount: number)

The demo output is labeled (currencies:), so every printed line can be matched to the operation behind it.

Key statements

return Object.assign(format, { currency });

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `format`, `makeFormatter` at load time.