6.4 Destructuring Parameter Declarations

Parameter declarations can specify binding patterns (section 3.9.2.2) and are then called destructuring parameter declarations. Similar to a destructuring variable declaration (section 5.2.2), a destructuring parameter declaration introduces zero or more named locals and initializes them with values extracted from properties or elements of the object or array passed as an argument for the parameter.

The type of local introduced in a destructuring parameter declaration is determined in the same manner as a local introduced by a destructuring variable declaration, except the type T associated with a destructuring parameter declaration is determined as follows:

  • If the declaration includes a type annotation, T is that type.
  • If the declaration occurs in a function expression for which a contextual signature is available (section 4.10), T is the type obtained from the contextual signature.
  • Otherwise, if the declaration includes an initializer expression, T is the widened form (section 3.12) of the type of the initializer expression.
  • Otherwise, if the declaration specifies a binding pattern, T is the implied type of that binding pattern (section 5.2.3).
  • Otherwise, if the parameter is a rest parameter, T is any[].
  • Otherwise, T is any.

When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations.

The example

  1. function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) {
  2. // Draw text
  3. }

declares a function drawText that takes a single parameter of the type

  1. { text?: string; location?: [number, number]; bold?: boolean; }

When the output target is ECMAScript 3 or 5, the function is rewritten to

  1. function drawText(_a) {
  2. var _b = _a.text,
  3. text = _b === void 0 ? "" : _b,
  4. _c = _a.location,
  5. _d = _c === void 0 ? [0, 0] : _c,
  6. x = _d[0],
  7. y = _d[1],
  8. _e = _a.bold,
  9. bold = _e === void 0 ? false : _e;
  10. // Draw text
  11. }

Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. Type annotations must instead be written on the top-level parameter declaration. For example

  1. interface DrawTextInfo {
  2. text?: string;
  3. location?: [number, number];
  4. bold?: boolean;
  5. }
  6. function drawText({ text, location: [x, y], bold }: DrawTextInfo) {
  7. // Draw text
  8. }