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.
Code
// 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 EURInside 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
JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.