TypeScript Reference ยท Type Operators
TypeScript destructuring
Reference for TypeScript destructuring: object and array patterns, defaults, renaming, rest elements, nested patterns and how to annotate them.
Destructuring unpacks values from objects and arrays into variables with a pattern. TypeScript infers each variable's type from the source, so you rarely annotate the pattern itself. When you do need types, annotate the whole pattern, not the individual names.
Patterns work in declarations, assignments, function parameters, for...of loops and catch clauses. They support defaults, renaming, nesting and rest elements.
const point = { x: 1, y: 2 }; const { x, y: height } = point; // x: number, height: number
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
const { a, b: renamed = defaultValue, ...rest } = object; const [x, , y = 0, ...others] = iterable; function f({ a, b }: { a: number; b: string }) {}
| Piece | Description |
|---|---|
{ a } |
Reads property a into a variable of the same name. |
{ a: b } |
Reads a into a variable named b. The colon renames, it does not annotate. |
= value |
Default used when the value is undefined (not for null). |
...rest |
Collects remaining own properties, or remaining array elements. |
[ , x] |
A hole skips a position. |
Types: a default makes the variable's type exclude undefined. With noUncheckedIndexedAccess, array destructuring from T[] gives T | undefined. Destructuring null or undefined throws a TypeError at runtime and is rejected by the compiler when the type allows it.
Usage notes
- Rename versus annotate:
{ name: string }means "putnameinto a variable calledstring". Write{ name }: { name: string }instead. - Defaults only for
undefined. Anullvalue passes through; use??afterward if you want to replace it. - Rest in objects copies own enumerable properties and the type omits the destructured keys.
- Array patterns work on iterables, including strings, Sets and Maps (entries).
- Tuple length is checked: destructuring a third element from a two-element tuple is an error.
- Parameter destructuring documents the expected shape right in the signature, but long patterns are easier to read as a named type.
- Assignment form needs parentheses for objects:
({ a, b } = source);.
Related
- Spread (...), Optional chaining, Partial
- Tutorial: Objects, Arrays and tuples