Choose between type and interface with one rule: an object’s outline is an interface, everything else is a type. See that interface names only outlines, that two interfaces with one name merge while two type aliases are a Duplicate identifier, and switch TaskKit’s Task to an interface.
Fundamentals
TypeScript
`type` or `interface`: a simple rule for choosing. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson you had two ways to write the same
outline: type Task = { … }; and interface Task { … }. Both give it
a name, and TypeScript checks a value against both in the same way,
with the same message, word for word. So every time you start a new
outline, a small question is waiting for you: which one this time?
Answer it one way today and the other way tomorrow, and your files end
up with both. Whoever reads them stops at each one and wonders whether
the difference means something.
A kitchen you share works the same way. The cups could go on the left
shelf or the right one, and both would work. What saves everyone time
is that somebody decided once, cups on the left, and nobody thinks
about it again. In this lesson you get that rule for types: one
question that decides, for every type you name, which keyword to
write. On the way you meet the places where type and interface
really differ: what each can name, what happens when a name is written
twice, and which one takes extends. By the end, TaskKit's Task
follows the rule.
What only type can name
The two keywords do not do the same jobs. interface was made for one
job: the outline of an object. type names any type at all. In lesson
6.3 you gave a plain number a name, type Minutes = number;, and you
have met two more types that are not outlines: a tuple like [string, number] in lesson 4.6, and a function type like (task: string) => boolean in lesson 5.4. Each of them can have a name, and each name is
written with type. Here is what happens when each one, and an
object's outline, is written with each keyword. A refusal in the grid
shows the message's number, TS1005 (TS for TypeScript, then the
number of this message). Read the grid by rows:
What you nametypeinterfaceTask, an outline
Fits
Any type.
Fits
Made for it.
Minutes, a number
Fits
Any type.
Refused:TS1005
Not an outline.
Entry, a tuple
Fits
Any type.
type names anything; interface names only an object's outline
Write interface Minutes = number; and TypeScript stops at the =
with '{' expected., the message you met in the last lesson's
common mistake. After interface and a name, only an outline in
braces may follow. So the first row is the only one where you have
a choice at all: an object's outline can be either.
Here are the three names at work in one program:
It prints Calls: 25 min (min is short for minutes). Read the
first line of minutesIf aloud and the names do the explaining: it
takes a plan of entries and a rule, and gives back minutes.
One name, written twice
There is one more difference, and you can run into it without meaning
to. In a long file, or after copying a block from somewhere else, the
same name can end up written twice. What happens next depends on the
keyword.
Two type aliases with one name are refused straight away:
TypeScript marks both type Task lines with Duplicate identifier 'Task'. (here identifier is TypeScript's word for a name in the
code, not a task's id: the name Task is made twice). A name made by
type is made once, and a second one is a mistake TypeScript points
at. The figure stops at the second, where the name is made again.
Two interfaces with one name are not refused for the name. TypeScript
joins them into one outline, with the properties of both. This is
called declaration merging: two declarations, the lines that make
a name, merged into one. In the figure, the first Task has title
and the second has done. Switch between the three cases: two type
aliases; two interfaces, with a value that has only a title; and the
same two once the value has done too. Press Next step to walk
through each one, or let it play:
First Task: reachedHas title: string
Second Task: stops here✕May the name be used again?
Task: never reachedOpened: title, and done
The value: never reachedDoes it fit all of Task?
Node: never reachedRuns every line
Second Task stops hereDuplicate identifier 'Task'.
A second type Task stops at once; a second interface Task
joins the first
All 3 steps shown.Step 1 of 3: First TaskStep 2 of 3: Second TaskStep 3 of 3: Second Task: stops here. Duplicate identifier 'Task'.
All 3 steps shown.
First Task: reachedHas title: string
Second Task: passes✓May the name be used again?
Task: reachedOpened: title, and done
The value: stops here✕Does it fit all of Task?
Node: never reachedRuns every line
The value stops hereProperty 'done' is missing in type '{ title: string; }'
but required in type 'Task'.
A second type Task stops at once; a second interface Task
joins the first
All 6 steps shown.Step 1 of 6: First TaskStep 2 of 6: Second TaskStep 3 of 6: Second Task: passesStep 4 of 6: TaskStep 5 of 6: The valueStep 6 of 6: The value: stops here. Property 'done' is missing in type '{ title: string; }'
but required in type 'Task'.
All 6 steps shown.
First Task: reachedHas title: string
Second Task: passes✓May the name be used again?
Task: reachedOpened: title, and done
The value: passes✓Does it fit all of Task?
Node: reachedRuns every line
A second type Task stops at once; a second interface Task
joins the first
All 7 steps shown.Step 1 of 7: First TaskStep 2 of 7: Second TaskStep 3 of 7: Second Task: passesStep 4 of 7: TaskStep 5 of 7: The valueStep 6 of 7: The value: passesStep 7 of 7: Node
All 7 steps shown.
Run the case with two interfaces:
TypeScript says nothing about the second interface Task. It stops at
the last line, with Property 'done' is missing in type '{ title: string; }' but required in type 'Task'. The value never mentions
done, and neither does the first interface Task: done came from
the second one. In a long file, the two can be far apart, and you see
only one. Add done: false to the value, and TypeScript accepts it
(the program prints nothing: it has no console.log).
So when a message asks for a property you never wrote on the outline
in front of you, search the file in VS Code (Visual Studio Code, your
editor) with its Find control for a second interface with the same
name:
⌘ Cmd+F
Ctrl+F
Ctrl+F
Better still, never give two outlines one name: one name,
one outline, written in one place. Bigger projects use merging on
purpose, to add properties to an outline written in another file;
Level 3 shows how. Until then, it is something to recognise, not
to use.
One rule
Now the choice comes down to one question about what you are naming:
is it the outline of an object? The answer gives you the keyword:
An object's outline: interface
Does: Every outline of an object, PlannedTask extends Task too
Anything else: type
Does: A number, a tuple, a function type: whatever is not an outline
The rule: an object's outline is an interface, everything
else a type
Why interface for outlines, when type could write them too?
Because interface does that one job and nothing else. When you read
interface, you know before the first brace that an object's outline
follows; in code that keeps the rule, type then tells you it is
something else. Merging is the price you can meet now (lesson 6.9
shows one more, with Object.entries): a second interface Task is
joined where a second type Task would be refused. Keep one name, one
outline, and you never pay it; and when the joined property is
required, as done is here, TypeScript still points at every value
that lacks it.
The TypeScript Handbook, the long guide from lesson 1.6, suggests the
same rule in its section Differences Between Type Aliases and
Interfaces, on the page Everyday
Types.
So you will find it in much of the code you read. And Module 7 brings
types that can only be written with type, so the rule already gives
you the keyword for them.
TaskKit: Task becomes an interface
TaskKit's Task is the outline of an object, so by the rule it is
an interface. Only the line that makes it changes.
1
Write Task as an interface
In index.ts in ~/projects/taskkit, find the line under the
import line at the top:
and replace it with:
printList and the line that makes the list still say Task, and
they stay as they are.
2
Check, run TaskKit, run the tests
npx tsc (tsc is short for TypeScript compiler, which npx
starts) prints nothing: the check passed. node --test still counts
pass 7.
Predict before you run
A planned task built on Task, and a second interface Task
further down the file. The value has a title and minutes. Decide
what TypeScript says about it before you run it.
Predict
TypeScript refuses the box call. Which property does it
say is missing?
The common mistake: extends on a type
You learned extends on an interface. When the outline you start from
is written with type, it is tempting to keep that keyword for the
new one as well.
Common mistake
Writing type PlannedTask extends Task { instead of interface
Task is a type alias, so the planned task is written as one too:
'=' expected.
The fix
extends belongs to interface. Both are outlines of objects, so by
the rule both are interfaces:
After type PlannedTask, TypeScript expects the = an alias always
has, and finds extends. One more message follows on that line, ';' expected.; it comes from the same extends, and goes when it does.
Node alone stops too, with Unexpected token `extends`. Expected =.
If Task is someone else's type that you cannot change, you only
need to change your own line: interface PlannedTask extends Task
works when Task is a type alias, as long as it names an object's
outline.
Pass all three 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
Which of these can only be named with type?
Check yourself
What happens to two interfaces both named Task?
Check yourself
Why write outlines with interface, when type can too?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
type or interface
What things are
Word
What it means
Declaration merging
Two interfaces with one name, joined into one
Code
Write
For
interface Task { … }
An object's outline, extends included
type Minutes = number;
A number
type Entry = [string, number];
A tuple
type Rule = (task: string) => boolean;
A function type
Rules
Rule
What it means
One question
An object's outline: interface; else type
Their project
Follow the rule it already uses
One name, one outline
Never give two outlines the same name
type Task twice
Duplicate identifier 'Task'.
interface Task twice
One outline: a value needs both
interface Minutes = …
'{' expected.
type … extends
'=' expected.
extends a type alias
Works when the alias names an outline
A property never written
Look for a second interface of that name
Node alone
Skips both keywords; never sees a name made twice
Where to go next
You can now pick the keyword for any name with one question, whether
it is an object's outline, and say why: interface does that one job,
and type names everything else. You also know where the two differ:
interface names only outlines and alone takes extends, and a name
written twice is refused as a type and joined as an interface.
TaskKit's Task is an interface now.
Next is Structural typing: shapes, not names; excess property
checks. There you find out what TypeScript really compares when
it checks a value, and why an object written straight into a call,
as in the last lesson's callout, is held to a stricter check than
the same object in a box.
Before you move on, go back to names.ts, press Edit, and give
the list of entries a name of its own: Plan, for Entry[]. Ask the
rule which keyword it takes before you write it, then use Plan in
minutesIf and run the program again.
Refused:TS1005
Not an outline.
Rule, a function type
Fits
Any type.
Refused:TS1005
Not an outline.
The keyword
Exercise · Read the code
Which pair follows the rule
Each answer names a task's outline and a number of minutes. Which
pair follows this lesson's rule?
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkTasks added: 3 of 5, room for 2 moreList 60% fullYour list, A to Z:#3 Buy milk, due: not set#2 Call Mom, due: not set#1 Pay rent, due: not set
names.tsts
type Minutes = number;type Entry = [string, number];type Rule = (task: string) => boolean;function isCall(task: string): boolean { return task.startsWith("call");}function minutesIf(plan: Entry[], rule: Rule): Minutes { let total = 0; for (const entry of plan) { if (rule(entry[0])) { total += entry[1]; } } return total;}const plan: Entry[] = [ ["call mom", 10], ["buy milk", 5], ["call the bank", 15],];console.log(`Calls: ${minutesIf(plan, isCall)} min`);