← 中文资源

简体中文版本

JSDoc 注解为纯 JS 提供类型

@typedef、@property、@param、@returns 直接写在注释里,就能让编辑器与 tsc --checkJS 校验纯 .js 文件的调用,不需要引入任何构建步骤。

阅读英文原文

运行结果

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

open invoices: 2
open cents: 2030

实现说明

逻辑集中在函数 unpaidTotals里。 返回值是携带 length、sum、cents 的对象。

常见问题

unpaidTotals 会修改传入的参数吗?

不会修改。入参只读,返回值是全新构造的。

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件在加载时定义 unpaidTotals。

入口签名:function unpaidTotals(invoices)

核心语句

const open = invoices.filter((invoice) => !invoice.paid);

代码示例

/**
 * @typedef {Object} Invoice
 * @property {string} id
 * @property {number} cents — integer cents only, never floats
 * @property {boolean} paid
 */

/**
 * Totals the unpaid invoices; money stays in integer cents.
 * @param {Invoice[]} invoices
 * @returns {{ open: number, openCents: number }}
 */
function unpaidTotals(invoices) {
  const open = invoices.filter((invoice) => !invoice.paid);
  return {
    open: open.length,
    openCents: open.reduce((sum, invoice) => sum + invoice.cents, 0),
  };
}

/** @type {Invoice[]} */
const invoices = [
  { id: 'inv-1', cents: 4950, paid: true },
  { id: 'inv-2', cents: 1200, paid: false },
  { id: 'inv-3', cents: 830, paid: false },
];

const totals = unpaidTotals(invoices);
console.log(`open invoices: ${totals.open}`);
console.log(`open cents: ${totals.openCents}`);
// The next line fails under tsc --checkJS: cents must be a number
// invoices.push({ id: 'inv-4', cents: '500', paid: false });