JSDoc Annotations Type Plain JavaScript

Give plain .js files real types with @typedef, @property, @param, and @returns so editors and tsc --checkJS validate calls without any build step.

JavascriptData Integrity

Code

javascriptsnippet
32 lines
/**
 * @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 });

Output

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

open invoices: 2
open cents: 2030

Under the hood

The code’s whole job belongs to the function unpaidTotals.

The result comes back as an object carrying length, sum, cents.

Points of care

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Using it

The entry-point signature is function unpaidTotals(invoices)

The run emits 2 labeled sections — open invoices: $, open cents: $ — one per step.

The call returns length, sum, cents — destructure what you need at the call site.

Key statements

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

Interactive Tools for This Topic

FAQ

Does `unpaidTotals` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `unpaidTotals` at load time.