← 中文资源

简体中文版本

调用签名描述可调用对象

用调用签名加属性描述可调用对象,通过 Object.assign 构造实例,并按接口直接调用。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

$19.50
€19.50
currencies: USD EUR

实现说明

值得阅读的是函数 format、makeFormatter,其余是驱动代码。

使用要点

  • 演示输出是带标签的(currencies:),每个操作都会留下自己的一行标注。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 format、makeFormatter。

签名一览:const format = (amount: number)

核心语句

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

代码示例

// 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);