Destructuring and spread (and why spread is shallow)
Take properties out of an object by name and items out of a tuple by place, copy an object or a list with three dots, and change what differs in the same braces. See why a spread copy still shares every list inside it, and copy that list too.
Fundamentals
TypeScript
Destructuring and spread (and why spread is shallow). Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Every spring the dentist hands you the same form: name, address,
phone. You copy last year's answers onto the new sheet and change
only the line that is different. You do not rewrite your street
from memory, and the old sheet stays as it was.
In the last lesson you made a real copy of a task by writing out
every property: { id: rent.id, title: rent.title, due: rent.due }.
That works, and it grows with every property a task gets. This
lesson gives you two short ways to work with an object's
properties: one takes them out into boxes of their own, the other
copies them all into a new object in one go. By the end you also
know the one place where that short copy still shares something
with the original, and how to stop it.
Take properties out: destructuring
TaskKit's printList writes task.id (id is short for identifier,
the task's number), task.title and task.due in one line, and a
bigger function writes them again and again. When you need a few
properties of one object, you can take them out once, each into a box
with a short name.
That is destructuring: braces on the left of = that list the
properties you want. const { title, due } = rent; makes two
const boxes, title and due, and fills each from the property
with the same name. It does exactly what these two lines do:
ts
const title = rent.title;const due = rent.due;
A tuple, lesson 4.6's list with a fixed type in each place, can be
taken apart the same way with square brackets. Here are an object
and a tuple to take apart:
The two kinds of brackets work differently. An object's
properties have names, and a tuple's items have places:
From an object
Does: Each box gets the property with the same name
Never: It never looks at the order of the names
From a tuple
Does: Each box gets the item in its place: first, then second
Never: It never looks at the names you choose
An object gives its properties by name; a tuple its items by
place
Run both:
It prints Pay rent Monday, then buy milk: 25 minutes. Paste these
lines into a new file, unpack.ts, in VS Code (Visual Studio Code,
your editor) and hover over due in const { title, due } = rent;:
it shows const due: string | undefined. due is optional in Task,
so the box may get undefined, and you read it with ?? from lesson
3.4. With let instead of const, the boxes can be refilled later,
like any let box.
A name in the braces must be a property of the object's type. const { date } = rent; is refused with Property 'date' does not exist on type 'Task'. (TS2339: TS for TypeScript, then the number of the
message), the same error rent.date gets.
Destructuring also works in a parameter. Write the braces where
the parameter's name would go, and the type after them:
It prints Pay rent, due: Monday and Buy milk, due: not set. The
function still takes one Task; it only names the two properties it
uses. A loop's box can be taken apart the same way: in printList,
for (const { title } of byName) fills title from each task in
turn.
Copy with spread
Now the copy from the last lesson, written short. Three dots in
front of an object, inside new braces, are spread: they copy
every property of that object into the new one.
{ ...rent } is a real copy of rent, made by the new braces,
however many properties a task has.
You met three dots in lesson 5.3, in front of a rest parameter,
where they gathered many values into one list. Spread does the
opposite: it spreads one object's properties out into the braces
it stands in.
After the spread you can write properties of your own, and the
braces are read left to right. Press Next step to walk through
{ ...rent, due: "Friday" }, or let it play:
1
{ }
New braces make a new object, empty so far.
2
...rent
Every property of rent is copied in: id, title, due.
3
due: "Friday"
due is written again, so "Friday" replaces "Monday".
The braces are read left to right; a later value replaces an
earlier one
All 3 steps shown.Step 1 of 3: { }Step 2 of 3: ...rentStep 3 of 3: due: "Friday"
All 3 steps shown.
That is the dentist's form: copy everything, change one line.
It prints Monday Friday, then false: later is a new object,
and rent keeps its Monday. This works for a readonly property too:
{ ...rent, id: 2 } changes nothing in rent. It writes id into a
new object, so readonly has nothing to refuse.
Spread works on lists too, inside square brackets.
[...week, "buy milk"] makes a new list with every item of week
and one more at the end, and [...week] alone is a copy of it:
It prints 2 3. Unlike push, which adds to the list it is
called on, spread leaves week as it was.
The same three dots hand a list to a function one item at a time.
Lesson 5.3's total takes its numbers with a rest parameter, and
TypeScript refused total(planned): a whole list, where the function
wanted numbers. Spread the list in the call:
It prints 40: total(...planned) is the same call as
total(25, 15).
Spread is shallow
A property can hold a list too. Give a task tags, short words
that group tasks, such as home or money: in the type it is
tags: string[]. Then copy a task with spread, and change both the
copy's tags and its title:
Spread copies each property the way = copies a value. A title is
text, so the copy gets its own. A list is an object, so the property
holds an arrow to it, and the copy gets a copy of the arrow. In the
boxes below, … stands for the id, which both have. #1, #2 and
#3 name the objects in memory, as in the last lesson. Inside an
object an arrow is written as text: tags: → #3 means the property
tags points at object #3. Look at the two tags: → #3: both objects
point at the same list, #3.
Variables
Values
const rent: Task points at shared value #1constrent: Task→ #1
const copy: Task points at shared value #2constcopy: Task→ #2
#1{…,title: "Pay rent",tags: → #3}
#2{…,title: "Pay bills",
Run it, and press Step to watch line 9 add a tag to the list that
rent.tags points at too:
It prints Pay rent [ 'home', 'money' ]. The title change stayed
in the copy, and the new tag did not. Spread makes a new object,
but only one level deep: what its properties point at is still
shared. That is a shallow copy. The copy you wrote out by hand
in the last lesson was shallow in the same way; its task simply
had no list inside.
To give the copy a list of its own, copy the list too, in the same
braces:
It prints 1 2. tags: [...rent.tags] comes after the spread, so
it replaces the copied arrow with an arrow to a new list. Each list
or object inside needs its own copy like this.
Destructuring is shallow in the same way. const { tags } = rent;
gives the box tags a copy of the arrow, so a push through
tags adds to rent's list.
Predict before you run
Here the spread comes last. Decide what the last line prints
before you run it.
Predict
What does the last line print?
The common mistake: tasks from one base task
Many tasks start alike. A base task, one you never use itself and only
copy from, saves you typing the same tags each time: make new tasks
from it with spread and change what differs.
Common mistake
Tasks made from one base task share its list of tags
Chores are tagged home. You make two chores from a base task, then
mark only the plants as today's job:
The dishes are tagged today too. Both spreads copied the base task's
arrow, so chore, dishes and plants share one list.
Wash the dishes [ 'home', 'today' ]
The fix
Give every task made from the base task a list of its own:
It prints Wash the dishes [ 'home' ]. TypeScript says nothing in
either version: sharing a list is allowed. When a change shows up
in objects you never touched, look for a spread whose object holds
a list or another object, and copy that inner part too.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What does const { title } = rent; do?
Check yourself
rent.due is "Monday". What is { ...rent, due: "Friday" }?
Check yourself
Which line gives copy a list of its own?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Destructuring and spread
What things are
Word
What it means
Destructuring
Taking properties or items out into boxes of their own
Spread
... copying every property or item into new brackets
Shallow copy
A new object whose inner lists are still shared
Code
Write
What happens
{ title, due } = rent
Two boxes, filled by property name
[task, minutes] = entry
Two boxes, filled by place
({ title, due }: Task)
A parameter taken apart
{ ...rent }
A new object with all of rent's properties
{ ...rent, due: day }
A copy with one property replaced
[...week, "buy milk"]
A new list, one item longer
total(...planned)
The items handed over one by one
tags: [...rent.tags]
The inner list copied too
Rules
Rule
What it means
Names must exist
{ date } = rent: TS2339
Left to right
A property after the spread replaces the copied one
Before the spread
Replaced by the copy; TS2783 if every Task has it
One level deep
Spread copies arrows, not what they point at
Destructuring too
A list taken out is the same list
Not a type error
TypeScript never warns about a shared list
Where to go next
You can now take properties out of an object by name and items out
of a tuple by place, copy an object or a list with three dots, and
change what differs in the same braces. You also know that a
spread copy shares every list inside it, and how to copy that list
too.
Next is Iterating over objects: Object.keys and
Object.entries. There you go through an object's properties one
by one, without knowing their names in advance, and the square
brackets you met here come back: each entry is a pair of a name and
a value, taken apart by place.
Before you move on, open TaskKit and take the task apart in
printList's loop: for (const { id, title, due } of byName).
Change the line inside to use id, title and due, then check,
run TaskKit and run the tests:
tsc is short for TypeScript compiler, which npx starts. The
output should not change by a single character.
tags: → #3
}
#3["home","money"]
Two objects, but spread copied the arrow to tags: one list
Exercise · Read the code
Refill one box, push to the other
Task has id, title and tags: string[], as in "Spread is
shallow". What does the last line print?
This program should print buy milk: 25 minutes, but it prints
25: buy milk minutes, and TypeScript says nothing. Fix the
destructuring line, and leave the rest as it is.
Loading the editor…
Exercise · Fix the error
Add a tag to a copy only
withTag should give back a copy of the task with one more tag,
and leave the task it is handed as it was. This program should
print 1 2, but it prints 2 2. Fix withTag, and leave the rest
as it is.
Loading the editor…
Exercise · Write the code
A label from two properties
Write label, which takes a Task and gives back its id and title as
#1 Pay rent, taking id and title out of it. The program should
then print #1 Pay rent and #2 Call Mom.