Píndoles JavaScript

JSDoc

JSDoc permet fer anotacions a JavaScript per a fer comprovacions de tipus i documentar el codi. Si s'utilitza VSCode podem activar aquesta comprovació afegint un arxiu jsconfig.json amb les propietats strict i checkJs:

{ "compilerOptions": { "strict": true, "checkJs": true } }

Variables

Podem definir el tipus d'una variable:

/** @type {number} */ let result1;

Si la definició té una assignació, JSDoc infereix el seu tipus i no caldria indicar-lo:

let result2 = 0;

Tot i que JavaScript ho permetria, JSDoc no permet canviar el tipus d'una variable.

Funcions

Podem documentar la funció, els seus paràmetres i el valor retornat.

/** * Add two numbers * @param {number} number1 * @param {number} number2 * @returns {number} */ function add(number1, number2) { return number1 + number2; }

JSDoc mostrarà un problema si intentem utilitzar aquesta funció amb un paràmetre que no sigui de tipus number, o bé si intentem assignar el resultat a una variable que no sigui number.

Tipus

Podem indicar els tipus entre dues claus.

  • Els primitius: boolean, string, number.
  • Els arrays, amb les claus quadrades, p. ex: string[].
  • Els objectes es poden definir amb @typedef.
/** * User object, surname is optional. * @typedef {Object} User * @property {number} id * @property {string} name * @property {string} [surname] * @property {boolean} active */
  • Les funcions callback es poden definir amb @callback, l'equivalent a typedef per a callbacks:
/** * A callback function applicable to a number * @callback ApplyFunc * @param {number} number * @returns {number} */

O bé directament utilitzant el tipus function:

/** @type {function(number):string} */ let stringerFn = (num) => (num.toString());
  • Podem definir que un paràmetre o variable pot tenir més d'un tipus amb l'OR.
/** @type {number | undefined} */
  • Podem fer casting de tipus:
const inputEl = /** @type {HTMLInputElement} */ (document.querySelector('input'));

És important utilitzar parèntesis sobre l'element castejat

  • Podem fer tipus condicional:
/** * @returns {string | number} */ function getValue() { return Math.random() > 0.5? String(17) : 17; } const value = getValue(); if (typeof value === 'string') { // type is string for this block console.log(`length is ${value.length}`); } if (typeof value === 'number') { // type is number for this block console.log(`square is ${value*value}`); }

Desactivació d'errors

Podem desactivar l'error de la línea següent amb:

// @ts-ignore

Podem desactivar tots els errors d'un arxiu amb:

// @ts-nocheck

o activar-los per a un arxiu, si per defecte estan desactivats, amb:

// @ts-check

Precedència d'operadors

Precedence Operator type Associativity Individual operators
18 Grouping n/a ( … )
17 Member Access left-to-right … . …
Optional chaining … ?. …
Computed Member Access n/a … [ … ]
new (with argument list) new … ( … )
Function Call … ( … )
16 new (without argument list) n/a new …
15 Postfix Increment n/a … ++
Postfix Decrement … --
14 Logical NOT (!) n/a ! …
Bitwise NOT (~) ~ …
Unary plus (+) + …
Unary negation (-) - …
Prefix Increment ++ …
Prefix Decrement -- …
typeof typeof …
void void …
delete delete …
await await …
13 Exponentiation (**) right-to-left … ** …
12 Multiplication (*) left-to-right … * …
Division (/) … / …
Remainder (%) … % …
11 Addition (+) left-to-right … + …
Subtraction (-) … - …
10 Bitwise Left Shift (<<) left-to-right … << …
Bitwise Right Shift (>>) … >> …
Bitwise Unsigned Right Shift (>>>) … >>> …
9 Less Than (<) left-to-right … < …
Less Than Or Equal (<=) … <= …
Greater Than (>) … > …
Greater Than Or Equal (>=) … >= …
in … in …
instanceof … instanceof …
8 Equality (==) left-to-right … == …
Inequality (!=) … != …
Strict Equality (===) … === …
Strict Inequality (!==) … !== …
7 Bitwise AND (&) left-to-right … & …
6 Bitwise XOR (^) left-to-right … ^ …
5 Bitwise OR (|) left-to-right … | …
4 Logical AND (&&) left-to-right … && …
3 Logical OR (||) left-to-right … || …
Nullish coalescing operator (??) … ?? …
2 Assignment right-to-left … = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
… &&= …
… ||= …
… ??= …
Conditional (ternary) operator right-to-left
(Groups on expressions after ?)
… ? … : …
Arrow (=>) right-to-left … => …
yield n/a yield …
yield* yield* …
Spread (...) ... …
1 Comma / Sequence left-to-right … , …