Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C5 · Lekcja 6
ZadanieDefine a @typedef Product with {id: number, title: string, priceCents: number, [discount]: number}. Write totalCents(items) where items is Product[] — applies discount (0-1) when present, sums priceCents. Log totalCents on two products: one with discount 0.1, one without.

JSDoc @typedef for object shapes

150 XP12 min
Teoria

Naming a shape once

When the same object shape shows up in multiple functions, repeating the inline JSDoc is noisy:

/** @param {{ id: number, name: string, isAdmin: boolean }} u */
function renderUser(u) { ... }

/** @param {{ id: number, name: string, isAdmin: boolean }} u */
function isStaff(u) { ... }

Give it a name with @typedef:

/**
 * @typedef {Object} User
 * @property {number} id
 * @property {string} name
 * @property {boolean} isAdmin
 */

/** @param {User} u */
function renderUser(u) { ... }

/** @param {User} u @returns {boolean} */
function isStaff(u) { return u.isAdmin; }

Why this matters

  • Rename a property once — every User reference re-checks.
  • Hovering "User" in the editor shows the full shape.
  • Future-you sees "this is a User" in three seconds, not thirty.

Optional properties

@property {string} [nickname] — the brackets mean optional. Same pattern as inline @param [name].

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.