100% found this document useful (1 vote)
47 views

Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript 1st Edition Josh Goldberg - Download the ebook in PDF with all chapters to read anytime

The document promotes the ebook 'Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript' by Josh Goldberg, available for download at ebookmeta.com. It includes endorsements from various professionals highlighting the book's clarity, practical examples, and effectiveness in teaching TypeScript. The author shares his journey with TypeScript and emphasizes its benefits for developers familiar with JavaScript.

Uploaded by

zaujahnimana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
47 views

Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript 1st Edition Josh Goldberg - Download the ebook in PDF with all chapters to read anytime

The document promotes the ebook 'Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript' by Josh Goldberg, available for download at ebookmeta.com. It includes endorsements from various professionals highlighting the book's clarity, practical examples, and effectiveness in teaching TypeScript. The author shares his journey with TypeScript and emphasizes its benefits for developers familiar with JavaScript.

Uploaded by

zaujahnimana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Learning TypeScript: Enhance Your Web Development


Skills Using Type-Safe JavaScript 1st Edition Josh
Goldberg

https://ebookmeta.com/product/learning-typescript-enhance-
your-web-development-skills-using-type-safe-javascript-1st-
edition-josh-goldberg/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Learning TypeScript: Enhance Your Web Development Skills


Using Type-Safe JavaScript Josh Goldberg

https://ebookmeta.com/product/learning-typescript-enhance-your-web-
development-skills-using-type-safe-javascript-josh-goldberg/

ebookmeta.com

Learning TypeScript: Enhance Your Web Development Skills


Using Type-Safe JavaScript 1st Edition Josh Goldberg

https://ebookmeta.com/product/learning-typescript-enhance-your-web-
development-skills-using-type-safe-javascript-1st-edition-josh-
goldberg/
ebookmeta.com

Connecting Arduino to the Web: Front End Development Using


JavaScript Indira Knight

https://ebookmeta.com/product/connecting-arduino-to-the-web-front-end-
development-using-javascript-indira-knight/

ebookmeta.com

Corrosion of Steel in Concrete 3rd Edition John P.


Broomfield

https://ebookmeta.com/product/corrosion-of-steel-in-concrete-3rd-
edition-john-p-broomfield/

ebookmeta.com
The Effectiveness of the UN Human Rights System Reform and
the Judicialisation of Human Rights 1st Edition Surya P.
Subedi
https://ebookmeta.com/product/the-effectiveness-of-the-un-human-
rights-system-reform-and-the-judicialisation-of-human-rights-1st-
edition-surya-p-subedi/
ebookmeta.com

Silk Slaves and Stupas Material Culture of the Silk Road


1st Edition Susan Whitfield

https://ebookmeta.com/product/silk-slaves-and-stupas-material-culture-
of-the-silk-road-1st-edition-susan-whitfield/

ebookmeta.com

The 11 Rules of Persuasion How to Master People s Emotions


Understand Their Intrinsic Motivations and Convince Them
of Your Ideas Incl NLP and Dark Psychology 2nd Edition
Matthew Bennett
https://ebookmeta.com/product/the-11-rules-of-persuasion-how-to-
master-people-s-emotions-understand-their-intrinsic-motivations-and-
convince-them-of-your-ideas-incl-nlp-and-dark-psychology-2nd-edition-
matthew-bennett/
ebookmeta.com

Why We Dream 1st Edition Alice Robb

https://ebookmeta.com/product/why-we-dream-1st-edition-alice-robb/

ebookmeta.com

Denying to the grave why we ignore the science that will


save us Jack M Gorman Sara E Gorman

https://ebookmeta.com/product/denying-to-the-grave-why-we-ignore-the-
science-that-will-save-us-jack-m-gorman-sara-e-gorman/

ebookmeta.com
The Law of Life and Death 1st Edition Elizabeth Price
Foley

https://ebookmeta.com/product/the-law-of-life-and-death-1st-edition-
elizabeth-price-foley/

ebookmeta.com
Praise for Learning TypeScript
If you ever screamed back at red squiggly lines in your code, then
go read Learning TypeScript. Goldberg masterfully puts everything
in context while staying practical, showing us that TypeScript is
never a restriction, but a valuable asset.
—Stefan Baumgartner, senior product architect,
Dynatrace; founder, oida.dev
Josh puts TypeScript’s most important concepts front and center,
and explains
them with clear examples and a touch of humor. A must-read for
the
JavaScript author who wants to write TypeScript like a pro.
—Andrew Branch, software engineer on TypeScript,
Microsoft
Learning TypeScript is an excellent resource for programmers who
have coded at least
a little before, but may have shied away from typed languages. It
goes
a level deeper than the TypeScript handbook to give you
confidence in using TypeScript in your own projects.
—Boris Cherny, software engineer, Meta;
author, Programming TypeScript
We don’t know what types code is but we’re very proud of Josh
and are sure it will be a lovely book.
—Frances and Mark Goldberg
Josh is that rare individual who is passionate about both acquiring
a deep command of the fundamentals and explaining concepts to
beginners. I think this book will quickly become a canonical
resource for TypeScript novices and experts alike.
—Beyang Liu, CTO and cofounder, Sourcegraph
Learning TypeScript is a fantastic introduction and reference to the
TS language. Josh’s writing is clear and informative, and that
helps with explaining often-confusing TS concepts and syntax. It’s
a great place to start for anyone new to TypeScript!
—Mark Erikson, senior frontend engineer, Replay;
maintainer, Redux
Learning TypeScript is a great book to start your TypeScript
journey. It gives you the tools to understand the language, the
type system, and the IDE integration, and
how to use all these to get the most out of your TypeScript
experience.
—Titian Cernicova Dragomir, software engineer,
Bloomberg LP
Josh has been a critical part of the TypeScript community for
many years, and
I’m really excited for folks to be able to benefit from his deep
understanding
and accessible teaching style through Learning TypeScript.
—James Henry, consultant architect, Nrwl; 4x
Microsoft MVP;
creator, angular-eslint and typescript-eslint
Josh is not just a very talented software engineer: he is also an
excellent mentor; you
can feel his passion for education throughout this book. Learning
TypeScript is
structured masterfully, and it contains practical, real-world
examples that will
take TypeScript newbies and enthusiasts to the next level. I can
confidently
say that Learning TypeScript is the definitive guide for anyone
looking
to learn or improve their knowledge about TypeScript.
—Remo Jansen, CEO, Wolk Software
In Learning TypeScript, Josh Goldberg breaks down TypeScript’s
most complex concepts into calm, straightforward descriptions and
digestible examples that are sure to serve
as a learning aid and reference for years to come. From the first
haiku
to the last joke, Learning TypeScript is a wonderful introduction
to the language that’s just my type. No pun intended.
—Nick Nisi, staff engineer, C2FO
They used to say, “Always bet on JavaScript.” Now it’s, “Always bet
on TypeScript,”
and this book will be the industry’s most recommended resource.
Guaranteed.
—Joe Previte, open source TypeScript engineer
Reading Learning TypeScript is like spending time with a warm
and smart friend who delights in telling you fascinating things.
You’ll walk away entertained and
educated about TypeScript whether you knew a lot or a little
beforehand.
—John Reilly, group principal engineer, Investec;
maintainer, ts-loader; Definitely Typed historian
Learning TypeScript is a comprehensive yet approachable guide to
the TypeScript language and ecosystem. It covers the broad
feature set of TypeScript
while providing suggestions and explaining trade-offs
based on broad experience.
—Daniel Rosenwasser, program manager, TypeScript,
Microsoft; TC39 representative
This is my favorite resource for learning TypeScript. From
introductory
to advanced topics, it’s all clear, concise, and comprehensive.
I found Josh to be an excellent—and fun—writer.
—Loren Sands-Ramshaw, author, The GraphQL
Guide; TypeScript SDK engineer, Temporal
If you are looking to be an effective TypeScript developer,
Learning TypeScript
has you covered all the way from beginning to advanced concepts.
—Basarat Ali Syed, principal engineer, SEEK;
author, Beginning NodeJS and TypeScript Deep Dive;
Youtuber (Basarat Codes); Microsoft MVP
This book is a great way to learn the language and
a perfect complement to the TypeScript Handbook.
—Orta Therox, ex-TypeScript compiler engineer,
Puzmo
Josh is one of the clearest and most dedicated TypeScript
communicators in the world, and his knowledge is finally in book
form! Beginners and experienced devs alike
will love the careful curation and sequencing of topics. The tips,
notes, and
warnings in the classic O’Reilly style are worth their weight in gold.
—Shawn “swyx” Wang, head of DX, Airbyte
This book will truly help you learn TypeScript. The theory chapters
together with the practice projects strike a good learning balance
and cover just about every aspect
of the language. Reviewing this book even taught this old dog
some new tricks.
I finally understand the subtleties of Declaration Files. Highly
recommended.
—Lenz Weber-Tronik, full stack developer, Mayflower
Germany; maintainer, Redux
Learning TypeScript is an accessible, engaging book that distills
Josh’s years of experience developing a TypeScript curriculum to
teach you everything you need to know
in just the right order. Whatever your programming background,
you’re in good hands with Josh and Learning TypeScript.
—Dan Vanderkam, senior staff software engineer,
Google; author, Effective TypeScript
Learning TypeScript is the book I wish I had when I first got into
TypeScript. Josh’s passion
for teaching new users oozes from every page. It’s thoughtfully
organized
into easily digestible chunks, and it covers everything
you need to become a TypeScript expert.
—Brad Zacher, software engineer, Meta;
core maintainer, typescript-eslint
Learning TypeScript
Enhance Your Web Development Skills Using Type-
Safe JavaScript

Josh Goldberg
Learning TypeScript
by Josh Goldberg
Copyright © 2022 Josh Goldberg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
[email protected].

Acquisitions Editor: Amanda Quinn

Development Editor: Rita Fernando

Production Editor: Clare Jensen

Copyeditor: Piper Editorial Consulting LLC

Proofreader: nSight, Inc.

Indexer: nSight, Inc.

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Kate Dullea

June 2022: First Edition


Revision History for the First Edition
2022-06-03: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781098110338 for


release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc.
Learning TypeScript, the cover image, and related trade dress are
trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not
represent the publisher’s views. While the publisher and the author
have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and
the author disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof
complies with such licenses and/or rights.
978-1-098-11033-8
[LSI]
Dedication
This book is dedicated to my incredible partner, Mariah, who
introduced me to the joy of adopting backyard cats and has
regretted it ever since. Toot.
Preface

My journey to TypeScript was not a direct or quick one. I started off


in school primarily writing Java, then C++, and like many new
developers raised on statically typed languages, I looked down on
JavaScript as “just” the sloppy little scripting language people throw
onto websites.
My first substantial project in the language was a silly remake of the
original Super Mario Bros. video game in pure HTML5/CSS/JavaScript
and, typical of many first projects, was an absolute mess. In the
beginning of the project I instinctively disliked JavaScript’s weird
flexibility and lack of guardrails. It was only toward the end that I
really began to respect JavaScript’s features and quirks: its flexibility
as a language, its ability to mix and match small functions, and its
ability to just work in user browsers within seconds of page load.
By the time I finished that first project, I had fallen in love with
JavaScript.
Static analysis (tools that analyze your code without running it) such
as TypeScript also gave me a queasy gut feeling at first. JavaScript is
so breezy and fluid, I thought, why bog ourselves down with rigid
structures and types? Were we reverting back to the worlds of Java
and C++ that I had left behind?
Coming back to my old projects, it took me all of 10 minutes of
struggling to read through my old, convoluted JavaScript code to
understand how messy things could get without static analysis. The
act of cleaning that code up showed me all the places I would have
benefited from some structure. From that point on, I was hooked
onto adding as much static analysis to my projects as I could.
It’s been nearly a decade since I first tinkered with TypeScript, and I
enjoy it as much as ever. The language is still evolving with new
features and is more useful than ever in providing safety and
structure to JavaScript.
I hope that by reading Learning TypeScript you can learn to
appreciate TypeScript the way I do: not just as a means to find bugs
and typos—and certainly not a substantial change to JavaScript code
patterns—but as JavaScript with types: a beautiful system for
declaring the way our JavaScript should work, and helping us stick to
it.

Who Should Read This Book


If you have an understanding of writing JavaScript code, can run
basic commands in a terminal, and are interested in learning about
TypeScript, this book is for you.
Maybe you’ve heard TypeScript can help you write a lot of JavaScript
with fewer bugs (true!) or document your code well for other people
to read (also true!). Maybe you’ve seen TypeScript show up in a lot
of job postings, or in a new role you’re starting.
Whatever your reason, as long as you come in knowing the
fundamentals of JavaScript—variables, functions, closures/scope,
and classes—this book will take you from no TypeScript knowledge
to mastering the fundamentals and most important features of the
language. By the end of this book, you will understand:

The history and context for why TypeScript is useful on top of


“vanilla” JavaScript
How a type system models code
How a type checker analyzes code
How to use development-only type annotations to inform the
type system
How TypeScript works with IDEs (Integrated Development
Environments) to provide code exploration and refactoring tools

And you will be able to:

Articulate the benefits of TypeScript and general characteristics


of its type system.
Add type annotations where useful in your code.
Represent moderately complex types using TypeScript’s built-in
inferences and new syntax.
Use TypeScript to assist local development in refactoring code.

Why I Wrote This Book


TypeScript is a wildly popular language in both industry and open
source:

GitHub’s 2021 and 2020 State of the Octoverses have it at the


platform’s fourth top language, up from seventh in 2019 and
2018 and tenth in 2017.
StackOverflow’s 2021 Developer Survey has it at the world’s
third most loved language (72.73% of users).
The 2020 State of JS Survey shows TypeScript has consistently
high satisfaction and usage amounts as both a build tool and
variant of JavaScript.

For frontend developers, TypeScript is well supported in all major UI


libraries and frameworks, including Angular, which strongly
recommends TypeScript, as well as Gatsby, Next.js, React, Svelte,
and Vue. For backend developers, TypeScript generates JavaScript
that runs natively in Node.js; Deno, a similar runtime by Node’s
creator, emphasizes directly supporting TypeScript files.
However, despite this plethora of popular project support, I was
rather disappointed by the lack of good introductory content online
when I first learned the language. Many of the online documentation
sources didn’t do a great job of explaining what a “type system” is or
how to use it. They often assumed a great deal of prior knowledge
in both JavaScript and strongly typed languages, or were written
with only cursory code examples.
Not seeing an O’Reilly book with a cute animal cover introducing
TypeScript years ago was a disappointment. While other books on
TypeScript from publishers including O’Reilly now exist prior to this
one, I couldn’t find a book that focuses on the foundations of the
language quite the way I wanted: why it works the way it does and
how its core features work together. A book that starts with a
foundational explanation of the language before adding on features
one-by-one. I’m thrilled to be able to make a clear, comprehensive
introduction to TypeScript language fundamentals for readers who
aren’t already familiar with its principles.

Navigating This Book


Learning TypeScript has two purposes:
You can read through it once to understand TypeScript as a
whole.
Later, you can refer back to it as a practical introductory
TypeScript language reference.

This book ramps up from concepts to practical use across three


general sections:

Part I, “Concepts”: How JavaScript came to be, what TypeScript


adds to it, and the foundations of a type system as TypeScript
creates it.
Part II, “Features”: Fleshing out how the type system interacts
with the major parts of JavaScript you’d work with when writing
TypeScript code.
Part III, “Usage”: Now that you understand the features that
make up the TypeScript language, how to use them in real-
world situations to improve your code reading and editing
experience.
I’ve thrown in a Part IV, “Extra Credit” section at the end to cover
lesser-used but still occasionally useful TypeScript features. You
won’t need to deeply know them to consider yourself a TypeScript
developer. But they’re all useful concepts that will likely come up as
you use TypeScript for real-world projects. Once you’ve finished
understanding the first three sections, I highly recommend studying
up on the extra credit section.
Each chapter starts with a haiku to get into the spirit of its contents
and ends with a pun. The web development community as a whole
and TypeScript’s community within it are known for being jovial and
welcoming of newcomers. I tried to make this book pleasant to read
for learners like me who don’t appreciate long, dry writings.

Examples and Projects


Unlike many other resources that introduce TypeScript, this book
intentionally focuses on introducing language features with
standalone examples showing just the new information rather than
delving into medium- or large-sized projects. I prefer this method of
teaching because it puts a spotlight on the TypeScript language first
and foremost. TypeScript is useful across so many frameworks and
platforms—many of which undergo API updates regularly—that I
didn’t want to keep anything framework- or platform-specific in this
book.
That being said, it is supremely useful when learning a programming
language to exercise concepts immediately after they’re introduced.
I highly recommend taking a break after each chapter to rehearse
that chapter’s contents. Each chapter ends with a suggestion to visit
its section on https://learningtypescript.com and work through the
examples and projects listed there.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file
extensions.

Constant width
Used for program listings, as well as within paragraphs to refer to
program elements such as variable or function names, data
types, statements, and keywords.

TIP
This element signifies a tip or suggestion.

NOTE
This element signifies a general note.

WARNING
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available
for download at https://learningtypescript.com.
If you have a technical question or a problem using the code
examples, please send email to [email protected].
This book is here to help you get your job done. In general, if
example code is offered with this book, you may use it in your
programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the
code. For example, writing a program that uses several chunks of
code from this book does not require permission. Selling or
distributing examples from O’Reilly books does require permission.
Answering a question by citing this book and quoting example code
does not require permission. Incorporating a significant amount of
example code from this book into your product’s documentation
does require permission.
We appreciate, but generally do not require, attribution. An
attribution usually includes the title, author, publisher, and ISBN. For
example: “Learning Typescript by Josh Goldberg (O’Reilly). Copyright
2022 Josh Goldberg, 978-1-098-11033-8.”
If you feel your use of code examples falls outside fair use or the
permission given above, feel free to contact us at
[email protected].

O’Reilly Online Learning

NOTE
For more than 40 years, O’Reilly Media has provided technology and business
training, knowledge, and insight to help companies succeed.
Our unique network of experts and innovators share their knowledge
and expertise through books, articles, and our online learning
platform. O’Reilly’s online learning platform gives you on-demand
access to live training courses, in-depth learning paths, interactive
coding environments, and a vast collection of text and video from
O’Reilly and 200+ other publishers. For more information, visit
http://oreilly.com.

How to Contact Us
Please address comments and questions concerning this book to the
publisher:

O’Reilly Media, Inc.

1005 Gravenstein Highway North

Sebastopol, CA 95472

800-998-9938 (in the United States or Canada)

707-829-0515 (international or local)

707-829-0104 (fax)

We have a web page for this book, where we list errata, examples,
and any additional information. You can access this page at
https://oreil.ly/learning-typescript.
Email [email protected] to comment or ask technical
questions about this book.
For news and information about our books and courses, visit
https://oreilly.com.
Find us on LinkedIn: https://linkedin.com/company/oreilly-media.
Follow us on Twitter: https://twitter.com/oreillymedia.
Watch us on YouTube: https://www.youtube.com/oreillymedia.

Acknowledgments
This book was a team effort, and I’d like to sincerely thank
everybody who made it possible. First and foremost my superhuman
editor-in-chief, Rita Fernando, for an incredible amount of patience
and excellent guidance throughout the authoring journey. Additional
shoutout to the rest of the O’Reilly crew: Kristen Brown, Suzanne
Huston, Clare Jensen, Carol Keller, Elizabeth Kelly, Cheryl Lenser,
Elizabeth Oliver, and Amanda Quinn. You all rock!
Many deep thanks to the tech reviewers for their consistently top-
notch pedagogical insights and TypeScript expertise: Mike Boyle,
Ryan Cavanaugh, Sara Gallagher, Michael Hoffman, Adam Reineke,
and Dan Vanderkam. This book wouldn’t be the same without you,
and I hope I successfully captured the intent of all your great
suggestions!
Further thanks to the assorted peers and praise quoters who gave
spot reviews on the book that helped me improve technical accuracy
and writing quality: Robert Blake, Andrew Branch, James Henry,
Adam Kaczmarek, Loren Sands-Ramshaw, Nik Stern, and Lenz
Weber-Tronic. Every suggestion helps!
Lastly, I’d like to thank my family for their love and support over the
years. My parents, Frances and Mark, and brother, Danny—thanks
for letting me spend time with Legos and books and video games. To
my spouse Mariah Goldberg for her patience during my long bouts of
editing and writing, and our cats Luci, Tiny, and Jerry for
distinguished fluffiness and keeping me company.
Part I. Concepts
Chapter 1. From JavaScript to
TypeScript

JavaScript today
Supports browsers decades past
Beauty of the web
Before talking about TypeScript, we need to first understand where it
came from: JavaScript!

History of JavaScript
JavaScript was designed in 10 days by Brendan Eich at Netscape in
1995 to be approachable and easy to use for websites. Developers
have been poking fun at its quirks and perceived shortcomings ever
since. I’ll cover some of them in the next section.
JavaScript has evolved tremendously since 1995, though! Its
steering committee, TC39, has released new versions of ECMAScript
—the language specification that JavaScript is based on—yearly
since 2015 with new features that bring it in line with other modern
languages. Impressively, even with regular new language versions,
JavaScript has managed to maintain backward compatibility for
decades in varying environments, including browsers, embedded
applications, and server runtimes.
Today, JavaScript is a wonderfully flexible language with a lot of
strengths. One should appreciate that while JavaScript has its quirks,
it’s also helped enable the incredible growth of web applications and
the internet.
Show me the perfect programming language and I’ll show you a
language with no users.
—Anders Hejlsberg, TSConf 2019

Vanilla JavaScript’s Pitfalls


Developers often refer to using JavaScript without any significant
language extensions or frameworks as “vanilla”: referring to it being
the familiar, original flavor. I’ll soon go over why TypeScript adds just
the right flavor to overcome these particular major pitfalls, but it’s
useful to understand just why they can be painful. All these
weaknesses become more pronounced the larger and longer-lived a
project gets.

Costly Freedom
Many developers’ biggest gripe with JavaScript is unfortunately one
of its key features: JavaScript provides virtually no restrictions in
how you structure your code. That freedom makes it a ton of fun to
start a project in JavaScript!
As you get to have more and more files, though, it becomes
apparent how that freedom can be damaging. Take the following
snippet, presented out of context from some fictional painting
application:

function paintPainting(painter, painting) {


return painter
.prepare()
.paint(painting, painter.ownMaterials)
.finish();
}

Reading that code without any context, you can only have vague
ideas on how to call the paintPainting function. Perhaps if
you’ve worked in the surrounding codebase you may recall that
painter should be what’s returned by some getPainter function.
You might even make a lucky guess that painting is a string.
Even if those assumptions are correct, though, later changes to the
code may invalidate them. Perhaps painting is changed from a
string to some other data type, or maybe one or more of the
painter’s methods are renamed.
Other languages might refuse to let you run code if their compiler
determines it would likely crash. Not so with dynamically typed
languages—those that run code without checking if it will likely crash
first—such as JavaScript.
The freedom of code that makes JavaScript so fun becomes a real
pain when you want safety in running your code.

Loose Documentation
Nothing exists in the JavaScript language specification to formalize
describing what function parameters, function returns, variables, or
other constructs in code are meant to be. Many developers have
adopted a standard called JSDoc to describe functions and variables
using block comments. The JSDoc standard describes how you might
write documentation comments placed directly above constructs
such as functions and variables, formatted in a standard way. Here’s
an example, again taken out of context:

/**
* Performs a painter painting a particular painting.
*
* @param {Painting} painter
* @param {string} painting
* @returns {boolean} Whether the painter painted the
painting.
*/
function paintPainting(painter, painting) { /* ... */ }
JSDoc has key issues that often make it unpleasant to use in a large
codebase:
Nothing stops JSDoc descriptions from being wrong about code.
Even if your JSDoc descriptions were previously correct, during
code refactors it can be difficult to find all the now-invalid JSDoc
comments related to your changes.
Describing complex objects is unwieldy and verbose, requiring
multiple standalone comments to define types and their
relationships.
Maintaining JSDoc comments across a dozen files doesn’t take up
too much time, but across hundreds or even thousands of constantly
updating files can be a real chore.

Weaker Developer Tooling


Because JavaScript doesn’t provide built-in ways to identify types,
and code easily diverges from JSDoc comments, it can be difficult to
automate large changes to or gain insights about a codebase.
JavaScript developers are often surprised to see features in typed
languages such as C# and Java that allow developers to perform
class member renamings or jump to the place an argument’s type
was declared.

NOTE
You may protest that modern IDEs such as VS Code do provide some
development tools such as automated refactors to JavaScript. True, but: they
use TypeScript or an equivalent under the hood for many of their JavaScript
features, and those development tools are not as reliable or as powerful in most
JavaScript code as they are in well-defined TypeScript code.
TypeScript!
TypeScript was created internally at Microsoft in the early 2010s then
released and open sourced in 2012. The head of its development is
Anders Hejlsberg, notable for also having lead the development of
the popular C# and Turbo Pascal languages. TypeScript is often
described as a “superset of JavaScript” or “JavaScript with types.”
But what is TypeScript?
TypeScript is four things:
Programming language
A language that includes all the existing JavaScript syntax, plus
new TypeScript-specific syntax for defining and using types

Type checker
A program that takes in a set of files written in JavaScript and/or
TypeScript, develops an understanding of all the constructs
(variables, functions…) created, and lets you know if it thinks
anything is set up incorrectly

Compiler
A program that runs the type checker, reports any issues, then
outputs the equivalent JavaScript code

Language service
A program that uses the type checker to tell editors such as VS
Code how to provide helpful utilities to developers

Getting Started in the TypeScript Playground


You’ve read a good amount about TypeScript by now. Let’s get you
writing it!
The main TypeScript website includes a “Playground” editor at
https://www.typescriptlang.org/play. You can type code into the
main editor and see many of the same editor suggestions you would
see when working with TypeScript locally in a full IDE (Integrated
Development Environment).
Most of the snippets in this book are intentionally small and self-
contained enough that you could type them out in the Playground
and tinker with them for fun.

TypeScript in Action
Take a look at this code snippet:

const firstName = "Georgia";


const nameLength = firstName.length();
// ~~~~~~
// This expression is not callable.

The code is written in normal JavaScript syntax—I haven’t


introduced TypeScript-specific syntax yet. If you were to run the
TypeScript type checker on this code, it would use its knowledge
that the length property of a string is a number—not a function—
to give you the complaint shown in the comment.
If you were to paste that code into the playground or an editor, it
would be told by the language service to give you a little red
squiggly under length indicating TypeScript’s displeasure with your
code. Hovering over the squigglied code would give you the text of
the complaint (Figure 1-1).
Figure 1-1. TypeScript reporting an error on string length not being callable

Being told of these simple errors in your editor as you type them is a
lot more pleasant than waiting until a particular line of code happens
to be run and throw an error. If you tried to run that code in
JavaScript, it would crash!

Freedom Through Restriction


TypeScript allows us to specify what types of values may be provided
for parameters and variables. Some developers find having to
explicitly write out in your code how particular areas are supposed to
work to be restrictive at first.
But! I would argue that being “restricted” in this way is actually a
good thing! By restricting our code to only being able to be used in
the ways you specify, TypeScript can give you confidence that
changes in one area of code won’t break other areas of code that
use it.
If, say, you change the number of required parameters for a
function, TypeScript will let you know if you forget to update a place
that calls the function.
In the following example, sayMyName was changed from taking in
two parameters to taking one parameter, but the call to it with two
strings wasn’t updated and so is triggering a TypeScript complaint:

// Previously: sayMyName(firstName, lastNameName) { ...


function sayMyName(fullName) {
console.log(`You acting kind of shady, ain't callin' me
${fullName}`);
}

sayMyName("Beyoncé", "Knowles");
// ~~~~~~~~~
// Expected 1 argument, but got 2.

That code would run without crashing in JavaScript, but its output
would be different from expected (it wouldn’t include "Knowles"):

You acting kind of shady, ain't callin' me Beyoncé

Calling functions with the wrong number of arguments is exactly the


sort of short-sighted JavaScript freedom that TypeScript restricts.

Precise Documentation
Let’s look at a TypeScript-ified version of the paintPainting
function from earlier. Although I haven’t yet gone over the specifics
of TypeScript syntax for documenting types, the following snippet
still hints at the great precision with which TypeScript can document
code:

interface Painter {
finish(): boolean;
ownMaterials: Material[];
paint(painting: string, materials: Material[]): boolean;
}

function paintPainting(painter: Painter, painting: string):


boolean { /* ... */ }

A TypeScript developer reading this code for the first time could
understand that painter has at least three properties, two of
which are methods. By baking in syntax to describe the “shapes” of
objects, TypeScript provides an excellent, enforced system for
describing how objects look.

Stronger Developer Tooling


TypeScript’s typings allow editors such as VS Code to gain much
deeper insights into your code. They can then use those insights to
surface intelligent suggestions as you type. These suggestions can
be incredibly useful for development.
If you’ve used VS Code to write JavaScript before, you might have
noticed that it suggests “autocompletions” as you write code with
built-in types of objects like strings. If, say, you start typing the
member of something known to be a string, TypeScript can suggest
all the members of the strings (Figure 1-2).

Figure 1-2. TypeScript providing autocompletion suggestions in JavaScript for a


string

When you add TypeScript’s type checker for understanding code, it


can give you these useful suggestions even for code you’ve written.
Upon typing painter. in the paintPainting function, TypeScript
would take its knowledge that the painter parameter is of type
Painter and the Painter type has the following members
(Figure 1-3).

Figure 1-3. TypeScript providing autocompletion suggestions in JavaScript for a


string

Snazzy! I’ll cover a plethora of other useful editor features in


Chapter 12, “Using IDE Features”.

Compiling Syntax
TypeScript’s compiler allows us to input TypeScript syntax, have it
type checked, and get the equivalent JavaScript emitted. As a
convenience, the compiler may also take modern JavaScript syntax
and compile it down into its older ECMAScript equivalents.
If you were to paste this TypeScript code into the Playground:

const artist = "Augusta Savage";


console.log({ artist });

The Playground would show you on the right-hand side of the screen
that this would be the equivalent JavaScript output by the compiler
(Figure 1-4).
Figure 1-4. TypeScript Playground compiling TypeScript code into equivalent
JavaScript

The TypeScript Playground is a great tool for showing how source


TypeScript becomes output JavaScript.

NOTE
Many JavaScript projects use dedicated transpilers such as Babel
(https://babeljs.io) instead of TypeScript’s own to transpile source code into
runnable JavaScript. You can find a list of common project starters on
https://learningtypescript.com/starters.

Getting Started Locally


You can run TypeScript on your computer as long as you have
Node.js installed. To install the latest version of TypeScript globally,
run the following command:

npm i -g typescript

Now, you’ll be able to run TypeScript on the command line with the
tsc (TypeScript Compiler) command. Try it with the --version
flag to make sure it’s set up properly:

tsc --version
It should print out something like Version X.Y.Z—whichever
version is current as of you installing TypeScript:

$ tsc --version
Version 4.7.2

Running Locally
Now that TypeScript is installed, let’s have you set up a folder locally
to run TypeScript on code. Create a folder somewhere on your
computer and run this command to create a new tsconfig.json
configuration file:

tsc --init

A tsconfig.json file declares the settings that TypeScript uses when


analyzing your code. Most of the options in that file aren’t going to
be relevant to you in this book (there are a lot of uncommon edge
cases in programming that the language needs to account for!). I’ll
cover them in Chapter 13, “Configuration Options”. The important
feature is that now you can run tsc to tell TypeScript to compile all
the files in that folder and TypeScript will refer to that tsconfig.json
for any configuration options.
Try adding a file named index.ts with the following contents:

console.blub("Nothing is worth more than laughter.");

Then, run tsc and provide it the name of that index.ts file:

tsc index.ts

You should get an error that looks roughly like:

index.ts:1:9 - error TS2339: Property 'blub' does not exist


on type 'Console'.
1 console.blub("Nothing is worth more than laughter.");
~~~~

Found 1 error.

Indeed, blub does not exist on the console. What was I thinking?
Before you fix the code to appease TypeScript, note that tsc
created an index.js for you with contents including the
console.blub.

NOTE
This is an important concept: even though there was a type error in our code,
the syntax was still completely valid. The TypeScript compiler will still produce
JavaScript from an input file regardless of any type errors.

Correct the code in index.ts to call console.log and run tsc


again. There should be no complaints in your terminal, and the
index.js file should now contain updated output code:

console.log("Nothing is worth more than laughter.");

TIP
I highly recommend playing with the book’s snippets as you read through them,
either in the playground or in an editor with TypeScript support, meaning it runs
the TypeScript language service for you. Small self-contained exercises, as well
as larger projects, are also available to help you practice what you’ve learned on
https://learningtypescript.com.
Editor Features
Another benefit of creating a tsconfig.json file is that when editors
are opened to a particular folder, they will now recognize that folder
as a TypeScript project. For example, if you open VS Code in a
folder, the settings it uses to analyze your TypeScript code will
respect whatever’s in that folder’s tsconfig.json.
As an exercise, go back through the code snippets in this chapter
and type them in your editor. You should see drop-downs suggesting
completions for names as you type them, especially for members
such as the log on console.
Very exciting: you’re using the TypeScript language service to help
yourself write code! You’re on your way to being a TypeScript
developer!

TIP
VS Code comes with great TypeScript support and is itself built in TypeScript.
You don’t have to use it for TypeScript—virtually all modern editors have
excellent TypeScript support either built-in or available via plugins—but I do
recommend it for at least trying out TypeScript while reading through this book.
If you do use a different editor, I also recommend enabling its TypeScript
support. I’ll cover editor features more deeply in Chapter 12, “Using IDE
Features”.

What TypeScript Is Not


Now that you’ve seen how wonderful TypeScript is, I have to warn
you about some limitations. Every tool excels at some areas and has
limitations in others.
A Remedy for Bad Code
TypeScript helps you structure your JavaScript, but other than
enforcing type safety, it doesn’t enforce any opinions on what that
structure should look like.
Good!
TypeScript is a language that everyone is meant to be able to use,
not an opinionated framework with a target audience. You can write
code using whatever architectural patterns you’re used to from
JavaScript, and TypeScript will support them.
If anybody tries to tell you that TypeScript forces you to use classes,
or makes it hard to write good code, or whatever code style
complaints are out there, give them a stern look and tell them to
pick up a copy of Learning TypeScript. TypeScript does not enforce
code style opinions such as whether to use classes or functions, nor
is it associated with any particular application framework—Angular,
React, etc.—over others.

Extensions to JavaScript (Mostly)


TypeScript’s design goals explicitly state that it should:

Align with current and future ECMAScript proposals


Preserve runtime behavior of all JavaScript code

TypeScript does not try to change how JavaScript works at all. Its
creators have tried very hard to avoid adding new code features that
would add to or conflict with JavaScript. Such a task is the domain of
TC39, the technical committee that works on ECMAScript itself.
There are a few older features in TypeScript that were added many
years ago to reflect common use cases in JavaScript code. Most of
those features are either relatively uncommon or have fallen out of
favor, and are only covered briefly in Chapter 14, “Syntax
Extensions”. I recommend staying away from them in most cases.

NOTE
As of 2022, TC39 is investigating adding a syntax for type annotations to
JavaScript. The latest proposals have them acting as a form of comments that
do not impact code at runtime and are used only for development-time systems
such as TypeScript. It will be many years until type comments or some
equivalent are added to JavaScript, so they won’t be mentioned elsewhere in
this book.

Slower Than JavaScript


Sometimes on the internet, you might hear some opinionated
developers complain that TypeScript is slower than JavaScript at
runtime. That claim is generally inaccurate and misleading. The only
changes TypeScript makes to code are if you ask it to compile your
code down to earlier versions of JavaScript to support older runtime
environments such as Internet Explorer 11. Many production
frameworks don’t use TypeScript’s compiler at all, instead using a
separate tool for transpilation (the part of compiling that converts
source code from one programming language into another) and
TypeScript only for type checking.
TypeScript does, however, add some time to building your code.
TypeScript code must be compiled down to JavaScript before most
environments, such as browsers and Node.js, will run it. Most build
pipelines are generally set up so that the performance hit is
negligible, and slower TypeScript features such as analyzing code for
likely mistakes are done separately from generating runnable
application code files.
NOTE
Even projects that seemingly allow running TypeScript code directly, such as ts-
node and Deno, themselves internally convert TypeScript code to JavaScript
before running it.

Finished Evolving
The web is nowhere near finished evolving, and thus neither is
TypeScript. The TypeScript language is constantly receiving bug fixes
and feature additions to match the ever-shifting needs of the web
community. The basic tenets of TypeScript you’ll learn in this book
will remain about the same, but error messages, fancier features,
and editor integrations will improve over time.
In fact, while this edition of the book was published with TypeScript
version 4.7.2 as the latest, by the time you started reading it, we can
be certain a newer version has been released. Some of the
TypeScript error messages in this book might even already be out of
date!

Summary
In this chapter, you read up on the context for some of JavaScript’s
main weaknesses, where TypeScript comes into play, and how to get
started with TypeScript:
A brief history of JavaScript
JavaScript’s pitfalls: costly freedom, loose documentation, and
weaker developer tooling
What TypeScript is: a programming language, a type checker, a
compiler, and a language service
TypeScript’s advantages: freedom through restriction, precise
documentation, and stronger developer tooling
Getting started writing TypeScript code on the TypeScript
Playground and locally on your computer
What TypeScript is not: a remedy for bad code, extensions to
JavaScript (mostly), slower than JavaScript, or finished evolving

TIP
Now that you’ve finished reading this chapter, practice what you’ve learned on
https://learningtypescript.com/from-javascript-to-typescript.

What happens if you spot errors running the TypeScript compiler?


You’d better go catch them!
Chapter 2. The Type System

JavaScript’s power
Comes from flexibility
Be careful with that!
I talked briefly in Chapter 1, “From JavaScript to TypeScript” about
the existence of a “type checker” in TypeScript that looks at your
code, understands how it’s meant to work, and lets you know where
you might have messed up. But how does a type checker work,
really?

What’s in a Type?
A “type” is a description of what a JavaScript value shape might be.
By “shape” I mean which properties and methods exist on a value,
and what the built-in typeof operator would describe it as.
For example, when you create a variable with the initial value
"Aretha":

let singer = "Aretha";

TypeScript can infer, or figure out, that the singer variable is of


type string.
The most basic types in TypeScript correspond to the seven basic
kinds of primitives in JavaScript:
null

undefined
boolean // true or false

string // "", "Hi!", "abc123", …


number // 0, 2.1, -4, …

bigint // 0n, 2n, -4n, …

symbol // Symbol(), Symbol("hi"), …

For each of these values, TypeScript understands the type of the


value to be one of the seven basic primitives:

null; // null

undefined; // undefined
true; // boolean

"Louise"; // string

1337; // number
1337n; // bigint

Symbol("Franklin"); // symbol

If you ever forget the name of a primitive, you can type a let
variable with a primitive value into the TypeScript Playground or an
IDE and hover your mouse over the variable’s name. The resultant
popover will include the name of the primitive, such as this
screenshot showing hovering over a string variable (Figure 2-1).

Figure 2-1. TypeScript showing a string variable’s type in its hover information
Discovering Diverse Content Through
Random Scribd Documents
in connection with it. The mixture of punctilio and decorum, on the one
hand, with passionate resentment and greed on the other, must be realised as
underlying all the transactions, and giving the leading psychological tone to
the natives’ interest. The obligation of fairness and decency is based on the
general rule, that it is highly improper and dishonourable to be mean. Thus,
though a man will generally strive to belittle the thing received, it must not
be forgotten that the man who gave it was genuinely eager to do his best.
And after all, in some cases when a man receives a really fine valuable, he
will boast of it and be frankly satisfied. Such a success is attributed of
course not to his partner’s generosity, but to his own magic.

A feature which is universally recognised as reprehensible and


discreditable, is a tendency to retain a number of valuables and be slow in
passing them on. A man who did this would be called “hard in the Kula.”
The following is a native description of this feature as exhibited by the
natives of the Amphletts.

“The Gumasila, their Kula is very hard; they are mean, they are retentive. They
would like to take hold of one soulava, of two, of three big ones, of four perhaps.
A man would pokala them, he would pokapokala; if he is a kinsman he will get a
soulava. The Kayleula only, and the Gumasila are mean. The Dobu, the Du’a’u,
the Kitava are good. Coming to Muyuwa—they are like Gumasila.”

This means that a man in Gumasila would let a number of necklaces


accumulate in his possession; would require plenty of food as pokala—a
characteristic reduplication describes the insistence and perseverance in
pokala—and even then he would give a necklace to a kinsman only. When I
inquired from the same informant whether such a mean man would also run
a risk of being killed by sorcery, he answered

“A man who is very much ahead in the Kula—he will die—the mean man not; he
will sit in peace.”
III

Returning now to the concrete proceedings of the Kula, let us follow the
movements of a Sinaketan toliwaga. He has presumably received a
necklace or two on his arrival; but he has more partners and he expects
more valuables. Before he receives his fill, he has to keep a taboo. He may
not partake of any local food, neither yams, nor coco-nuts, nor betel pepper
or nut. According to their belief, if he transgressed this taboo he would not
receive any more valuables. He tries also to soften the heart of his partner
by feigning disease. He will remain in his canoe and send word that he is ill.
The Dobu man will know what such a conventional disease means. None
the less, he may yield to this mode of persuasion. If this ruse does not
succeed, the man may have recourse to magic. There is a formula called
kwoygapani or ‘enmeshing magic,’ which seduces the mind of a man on
whom it is practised, makes him silly, and thus amenable to persuasion. The
formula is recited over a betel-nut or two, and these are given to the partner
and to his wife or sister.
Kwoygapani Spell
“O kwega leaf; O friendly kwega leaf; O kwega leaf hither; O kwega leaf thither!”

“I shall enter through the mouth of the woman of Dobu; I shall come out through
the mouth of the man of Dobu. I shall enter through the mouth of the man of
Dobu; I shall come out through the mouth of the woman of Dobu.”

“Seducing kwega leaf; enmeshing kwega leaf; the mind of the woman of Dobu is
seduced by the kwega leaf, is enmeshed by the kwega leaf.”

The expression “is seduced,” “is enmeshed “by the kwega leaf, is repeated with a
string of words such as: “Thy mind, O man of Dobu,” “thy refusal, O woman of
Dobu,” “Thy disinclination, O woman of Dobu,” “Thy bowels, thy tongue, thy
liver,” going thus over all the organs of understanding and feeling, and over the
words which describe these faculties. The last part is identical with that of one or
two formulæ previously quoted:

“No more it is my mother; my mother art thou, O woman of Dobu, etc.”


(Compare the Kaykakaya and Ka’ubana’i spells of the previous chapter.)

Kwega is a plant, probably belonging to the same family as betel pepper,


and its leaves are chewed with areca-nut and lime, when real betel-pods
(mwayye) are not available. The kwega is, remarkably enough, invoked in
more than one magical formula, instead of the real betel-pod. The middle
part is quite clear. In it, the seducing and enmeshing power of the kwega is
cast over all the mental faculties of the Dobuan, and on the anatomical seats
of these faculties. After the application of this magic, all the resources of the
soliciting man are exhausted. He has to give up hope, and take to eating the
fruit of Dobu, as his taboo lapses.

Side by side with the Kula, the subsidiary exchange of ordinary goods takes
place. In Chapter VI, Division VI, we have classified the various types of
give and take, as they are to be found in the Trobriand Islands. The inter-
tribal transactions which now take place in Dobu also fit into that scheme.
The Kula itself belongs to class (6), ‘Ceremonial Barter with deferred
payment.’ The offering of the pari, of landing gifts by the visitors, returned
by the talo’i or farewell gifts from the hosts fall into the class (4) of
presents more or less equivalent. Finally, between the visitors and the local
people there takes place, also, barter pure and simple (gimwali). Between
partners, however, there is never a direct exchange of the gimwali type. The
local man will as a rule contribute a bigger present, for the talo’i always
exceeds the pari in quantity and value, and small presents are also given to
the visitors during their stay. Of course, if in the pari there were included
gifts of high value, like a stone blade or a good lime spoon, such solicitary
gifts would always be returned in strictly equivalent form. The rest would
be liberally exceeded in value.

The trade takes place between the visitors and local natives, who are not
their partners, but who must belong to the community with whom the Kula
is made. Thus, Numanuma, Tu’utauna and Bwayowa are the three
communities which form what we have called the ‘Kula community’ or
‘Kula unit,’ with whom the Sinaketans stand in the relation of partnership.
And a Sinaketa man will gimwali (trade) only with a man from one of these
villages who is not his personal partner. To use a native statement:

“Some of our goods we give in pari; some we keep back; later on, we gimwali it.
They bring their areca-nut, their sago, they put it down. They want some article of
ours, they say: ‘I want this stone blade.’ We give it, we put the betel-nut, the sago
into our canoe. If they give us, however, a not sufficient quantity, we rate them.
Then they bring more.”

This is a clear definition of the gimwali, with haggling and adjustment of


equivalence in the act.

When the visiting party from Sinaketa arrive, the natives from the
neighbouring districts, that is, from the small island of Dobu proper, from
the other side of Dawson Straits, from Deyde’i, the village to the South,
will assemble in the three Kula villages. These natives from other districts
bring with them a certain amount of goods. But they must not trade directly
with the visitors from Boyowa. They must exchange their goods with the
local natives, and these again will trade them with the Sinaketans. Thus the
hosts from the Kula community act as intermediaries in any trading
relations between the Sinaketans and the inhabitants of more remote
districts.

To sum up the sociology of these transactions, we may say that the visitor
enters into a threefold relation with the Dobuan natives. First, there is his
partner, with whom he exchanges general gifts on the basis of free give and
take, a type of transaction, running side by side with the Kula proper. Then
there is the local resident, not his personal Kula partner, with whom he
carries on gimwali. Finally there is the stranger with whom an indirect
exchange is carried on through the intermediation of the local men. With all
this, it must not be imagined that the commercial aspect of the gathering is
at all conspicuous. The concourse of the natives is great, mainly owing to
their curiosity, to see the ceremonial reception of the uvalaku party. But if I
say that every visitor from Boyowa, brings and carries away about half-a-
dozen articles, I do not under-state the case. Some of these articles the
Sinaketan has acquired in the industrial districts of Boyowa during his
preliminary trading expedition (see Chapter VI, Division III). On these he
scores a definite gain. A few samples of the prices paid in Boyowa and
those received in Dobu will indicate the amount of this gain.

Kuboma to Sinaketa. Dobu to Sinaketa.


1 tanepopo basket = 12 coco-nuts = 12 coco-nuts + sago + 1 belt
1 comb = 4 coco-nuts = 4 coco-nuts + 1 bunch of betel
1 armlet = 8 coco-nuts = 8 coco-nuts + 2 bundles of betel
1 lime pot = 12 coco-nuts = 12 coco-nuts + 2 pieces of sago

This table shows in its second column the prices paid by the Sinaketans to
the industrial villages of Kuboma, a district in the Northern Trobriands. In
the third column what they receive in Dobu is recorded. The table has been
obtained from a Sinaketan informant, and it probably is far from accurate,
and the transactions are sure to vary greatly in the gain which they afford.
There is no doubt, however, that for each article, the Sinaketan would ask
the price which he paid for them as well as some extra article.
Thus we see that there is in this transaction a definite gain obtained by the
middlemen. The natives of Sinaketa act as intermediaries between the
industrial centres of the Trobriands and Dobu, whereas their hosts play the
same rôle between the Sinaketans and the men from the outlying districts.

Besides trading and obtaining of Kula valuables, the natives of Sinaketa


visit their friends and their distant relatives, who, as we saw before, are to
be found in this district owing to migrations. The visitors walk across the
flat, fertile plain from one hamlet to the other, enjoying some of the
marvellous and unknown sights of this district. They are shown the hot
springs of Numanuma and of Deyde’i, which are in constant eruption.
Every few minutes, the water boils up in one spring after another of each
group, throwing up jets of spray a few metres high. The plain around these
springs is barren, with nothing but here and there a stunted kind of
eucalyptus tree. This is the only place in the whole of Eastern New Guinea
where as far as I know, eucalyptus trees are to be found. This was at least
the information of some intelligent natives, in whose company I visited the
springs, and who had travelled all over the Eastern islands and the East end
of the mainland.

The land-locked bays and lagoons, the Northern end of Dawson Strait,
enclosed like a lake by mountains and volcanic cones, all this must also
appear strange and beautiful to the Trobrianders. In the villages, they are
entertained by their male friends, the language spoken by both parties being
that of Dobu, which differs completely from Kiriwinian, but which the
Sinaketans learn in early youth. It is remarkable that no one in Dobu speaks
Kiriwinian.

As said above, no sexual relations of any description take place between the
visitors and the women of Dobu. As one of the informants told me:

“We do not sleep with women of Dobu, for Dobu is the final mountain
(Koyaviguna Dobu); it is a taboo of the mwasila magic.”

But when I enquired, whether the results of breaking this taboo would be
baneful to their success in Kula only, the reply was that they were afraid of
breaking it, and that it was ordained of old (tokunabogwo ayguri) that no
man should interfere with the women of Dobu. As a matter of fact, the
Sinaketans are altogether afraid of the Dobuans, and they would take good
care not to offend them in any way.

After some three or four days’ sojourn in Dobu, the Sinaketan fleet starts on
its return journey. There is no special ceremony of farewell. In the early
morning, they receive their talo’i (farewell gifts) of food, betel-nut, objects
of use and sometimes also a Kula valuable is enclosed amongst the the
talo’i. Heavily laden as they are, they lighten their canoes by means of a
magic called kaylupa, and sail away northwards once more.

1 It will be noted, that this is the third meaning in which the term pokala is used by the
natives. (Cf. Chapter VI, Division VI.) ↑
Chapter XV
The Journey Home—The Fishing and Working of the
Kaloma Shell

The return journey of the Sinaketan fleet is made by following exactly the same
route as the one by which they came to Dobu. In each inhabited island, in every
village, where a halt had previously been made, they stop again, for a day or a few
hours. In the hamlets of Sanaroa, in Tewara and in the Amphletts, the partners are
revisited. Some Kula valuables are received on the way back, and all the talo’i gifts
from those intermediate partners are also collected on the return journey. In each of
these villages people are eager to hear about the reception which the uvalaku party
have received in Dobu; the yield in valuables is discussed, and comparisons are
drawn between the present occasion and previous records.

No magic is performed now, no ceremonial takes place, and there would be very
little indeed to say about the return journey but for two important incidents; the
fishing for spondylus shell (kaloma) in Sanaroa Lagoon, and the display and
comparison of the yield of Kula valuables on Muwa beach.

The natives of Sinaketa, as we have seen in the last chapter, acquire a certain
amount of the Koya produce by means of trade. There are, however, certain articles,
useful yet unobtainable in the Trobriands, and freely accessible in the Koya, and to
these the Trobrianders help themselves. The glassy forms of lava, known as
obsidian, can be found in great quantities over the slopes of the hills in Sanaroa and
Dobu. This article, in olden days, served the Trobrianders as material for razors,
scrapers, and sharp, delicate, cutting instruments. Pumice-stone abounding in this
district is collected and carried to the Trobriands, where it is used for polishing. Red
ochre is also procured there by the visitors, and so are the hard, basaltic stones
(binabina) used for hammering and pounding and for magical purposes. Finally,
very fine silica sand, called maya, is collected on some of the beaches, and imported
into the Trobriands, where it is used for polishing stone blades, of the kind which
serve as tokens of value and which are manufactured up to the present day.

II

But by far the most important of the articles which the Trobrianders collect for
themselves are the spondylus shells. These are freely, though by no means easily,
accessible in the coral outcrops of Sanaroa Lagoon. It is from this shell that the
small circular perforated discs (kaloma) are made, out of which the necklaces of the
Kula are composed, and which also serve for ornamenting almost all the articles of
value or of artistic finish which are used within the Kula district. But, only in two
localities within the district are these discs manufactured, in Sinaketa and in Vakuta,
both villages in Southern Boyowa. The shell can be found also in the Trobriand
Lagoon, facing these two villages. But the specimens found in Sanaroa are much
better in colour, and I think more easily procured. The fishing in this latter locality,
however, is done by the Sinaketans only.

Whether the fishing is done in their own Lagoon, near an uninhabited island called
Nanoula, or in Sanaroa, it is always a big, ceremonial affair, in which the whole
community takes part in a body. The magic, or at least part of it, is done for the
whole community by the magician of the kaloma (towosina kaloma), who also fixes
the dates, and conducts the ceremonial part of the proceedings. As the spondylus
shell furnishes one of the essential episodes of a Kula expedition, a detailed account
both of fishing and of manufacturing must be here given. The native name, kaloma
(in the Southern Massim districts the word sapi-sapi is used) describes both the
shell and the manufactured discs. The shell is the large spondylus shell, containing a
crystalline layer of a red colour, varying from dirty brick-red to a soft, raspberry
pink, the latter being by far the most prized. It lives in the cavities of coral outcrop,
scattered among shallow mud-bottomed lagoons.

This shell is, according to tradition, associated with the village of Sinaketa.
According to a Sinaketan legend, once upon a time, three guya’u (chief) women,
belonging to the Tabalu sub-clan of the Malasi clan, wandered along, each choosing
her place to settle in. The eldest selected the village of Omarakana; the second went
to Gumilababa; the youngest settled in Sinaketa. She had kaloma discs in her
basket, and they were threaded on a long, thin stick, called viduna, such as is used in
the final stage of manufacture. She remained first in a place called Kaybwa’u, but a
dog howled, and she moved further on. She heard again a dog howling, and she took
a kaboma (wooden plate) and went on to the fringing reef to collect shells. She
found there the momoka (white spondylus), and she exclaimed: “Oh, this is the
kaloma!” She looked closer, and said: “Oh no, you are not red. Your name is
momoka.” She took then the stick with the kaloma discs and thrust it into a hole of
the reef. It stood there, but when she looked at it, she said: “Oh, the people from
inland would come and see you and pluck you off.” She went, she pulled out the
stick; she went into a canoe, and she paddled. She paddled out into the sea. She
anchored there, pulled the discs off the stick, and she threw them into the sea so that
they might come into the coral outcrop. She said: “It is forbidden that the inland
natives should take the valuables. The people of Sinaketa only must dive.” Thus
only the Sinaketa people know the magic, and how to dive.

This myth presents certain remarkable characteristics. I shall not enter into its
sociology, though it differs in that respect from the Kiriwinian myths, in which the
equality of the Sinaketan and the Gumilababan chiefs with those of Omarakana is
not acknowledged. It is characteristic that the Malasi woman in this myth shows an
aversion to the dog, the totem animal of the Lukuba clan, a clan which according to
mythical and historical data had to recede before and yield its priority to the Malasi
(compare Chapter XII, Division IV). Another detail of interest is that she brings the
kaloma on their sticks, as they appear in the final stage of manufacturing. In this
form, also, she tries to plant them on the reef. The finished kaloma, however, to use
the words of one of my informants, “looked at her, the water swinging it to and fro;
flashing its red eyes.” And the woman, seeing it, pulls out the too accessible and too
inviting kaloma and scatters them over the deep sea. Thus she makes them
inaccessible to the uninitiated inland villagers, and monopolises them for Sinaketa.
There can be no doubt that the villages of Vakuta have learnt this industry from the
Sinaketans. The myth is hardly known in Vakuta, only a few are experts in diving
and manufacturing; there is a tradition about a late transference of this industry
there; finally the Vakutans have never fished for kaloma in the Sanaroa Lagoon.

Now let us describe the technicalities and the ceremonial connected with the fishing
for kaloma. It will be better to give an account of how this is done in the Lagoon of
Sinaketa, round the sandbank of Nanoula, as this is the normal and typical form of
kaloma fishing. Moreover, when the Sinaketans do it in Sanaroa, the proceedings
are very much the same, with just one or two phases missed out.

The office of magician of the kaloma (towosina kaloma) is hereditary in two sub-
clans, belonging to the Malasi clan, and one of them is that of the main chief of
Kasi’etana. After the Monsoon season is over, that is, some time in March or April,
ogibukuvi (i.e., in the season of the new yams) the magician gives the order for
preparations. The community give him a gift called sousula, one or two bringing a
vaygu’a, the rest supplying gugu’a (ordinary chattels), and some food. Then they
prepare the canoes, and get ready the binabina stones, with which the spondylus
shell will be knocked off the reef.

Next day, in the morning, the magician performs a rite called ‘kaykwa’una la’i,’ ‘the
attracting of the reef,’ for, as in the case of several other marine beings, the main
seat of the kaloma is far away. Its dwelling place is the reef Ketabu, somewhere
between Sanaroa and Dobu. In order to make it move and come towards Nanoula, it
is necessary to recite the above-named spell. This is done by the magician as he
walks up and down on the Sinaketa beach and casts his words into the open, over
the sea, towards the distant seat of the kaloma. The kaloma then ‘stand up’ (itolise)
that is start from their original coral outcrop (vatu) and come into the Lagoon of
Sinaketa. This spell, I obtained from To’udavada, the present chief of Kasi’etana,
and descendant of the original giver of this shell, the woman of the myth. It begins
with a long list of ancestral names; then follows a boastful picture of how the whole
fleet admires the magical success of the magician’s spell. The key-word in the main
part is the word ‘itolo’: ‘it stands up,’ i.e., ‘it starts,’ and with this, there are
enumerated all the various classes of the kaloma shell, differentiated according to
size, colour and quality. It ends up with another boast; “My canoe is overloaded
with shell so that it sinks,” which is repeated with varying phraseology.

Plate L (A)
Working the Kaloma Shell (I.)

The spondylus shell broken and made into roughly circular pieces by knocking all round; this is done
by men.
Plate L (B)
Working the Kaloma Shell (II.)

Women grinding pieces of shell into flat discs. Each piece is inserted into a hole at the end of a
wooden cylinder and ground on a flat sandstone.(See Div. III.)

This spell the magician may utter once only, or he may repeat it several times on
successive days. He fixes then the final date for the fishing expedition. On the
evening before that date, the men perform some private magic, every one in his own
house. The hammering stone, the gabila, which is always a binabina (it is a stone
imported from the Koya), is charmed over. As a rule it is put on a piece of dried
banana leaf with some red hibiscus blossoms and leaves or flowers of red colour. A
formula is uttered over it, and the whole is then wrapped up in the banana leaf and
kept there until it is used. This will make the stone a lucky one in hitting off many
shells, and it will make the shells very red.

Another rite of private magic consists in charming a large mussel shell, with which,
on the next morning, the body of the canoe will be scraped. This makes the sea
clear, so that the diver may easily see and frequently find his spondylus shells.
Next morning the whole fleet starts on the expedition. Some food has been taken
into the canoes, as the fishing usually lasts for a few days, the nights being spent on
the beach of Nanoula. When the canoes arrive at a certain point, about half-way
between Sinaketa and Nanoula, they all range themselves in a row. The canoe of the
magician is at the right flank, and he medicates a bunch of red hibiscus flowers,
some red croton leaves, and the leaves of the red-blossomed mangrove—red
coloured substances being used to make the shell red, magically. Then, passing in
front of all the other canoes, he rubs their prows with the bundle of leaves. After
that, the canoes at both ends of the row begin to punt along, the row evolving into a
circle, through which presently the canoe of the magician passes, punting along its
diameter. At this place in the Lagoon, there is a small vatu (coral outcrop) called
Vitukwayla’i. This is called the vatu of the baloma (spirits). At this vatu the
magician’s canoe stops, and he orders some of its crew to dive down and here to
begin the gathering of shells.

Some more private magic is performed later on by each canoe on its own account.
The anchor stone is charmed with some red hibiscus flowers, in order to make the
spondylus shell red. There is another private magic called ‘sweeping of the sea,’
which, like the magic of the mussel shell, mentioned above, makes the sea clear and
transparent. Finally, there is an evil magic called ‘besprinkling with salt water.’ If a
man does it over the others, he will annul the effects of their magic, and frustrate
their efforts, while he himself would arouse astonishment and suspicion by the
amount of shell collected. Such a man would dive down into the water, take some
brine into his mouth, and emerging, spray it towards the other canoes, while he
utters the evil charm.

So much for the magic and the ceremonial associated with the spondylus fishing in
the Trobriand Lagoon. In Sanaroa, exactly the same proceedings take place, except
that there is no attracting of the reef, probably because they are already at the
original seat of the kaloma. Again I was told that some of the private magic would
be performed in Sinaketa before the fleet sailed on the Kula expedition. The objects
medicated would be then kept, well wrapped in dried leaves.

It may be added that neither in the one Lagoon nor in the other are there any private,
proprietary rights to coral outcrops. The whole community of Sinaketa have their
fishing grounds in the Lagoon, within which every man may hunt for his spondylus
shell, and catch his fish at times. If the other spondylus fishing community, the
Vakutans, encroached upon their grounds, there would be trouble, and in olden days,
fighting. Private ownership in coral outcrops exists in the Northern villages of the
Lagoon, that is in Kavataria, and the villages on the island of Kayleula.
III

We must now follow the later stages of the kaloma industry. The technology of the
proceedings is so mixed up with remarkable sociological and economic
arrangements that it will be better to indicate it first in its main outlines. The
spondylus consists of a shell, the size and shape of a hollowed out half of a pear,
and of a flat, small lid. It is only the first part which is worked. First it has to be
broken into pieces with a binabina or an utukema (green stone imported from
Woodlark Island) as shown on Plate L (A). On each piece, then, can be seen the
stratification of the shell: the outside layer of soft, chalky substance; under this, the
layer of red, hard, calcareous material, and then the inmost, white, crystalline
stratum. Both the outside and inside have to be rubbed off, but first each piece has
to be roughly rounded up, so as to form a thick circular lump. Such a lump (see
foregrounds of Plates L (A), L (B)) is then put in the hole of a cylindrical piece of
wood. This latter serves as a handle with which the lumps are rubbed on a piece of
flat sandstone (see Plate L (B)). The rubbing is carried on so far till the outside and
inside layers are gone, and there remains only a red, flat tablet, polished on both
sides. In the middle of it, a hole is drilled through by means of a pump drill—gigi’u
—(see Plate LI), and a number of such perforated discs are then threaded on a thin,
but tough stick (see Plate LII), with which we have already met in the myth. Then
the cylindrical roll is rubbed round and round on the flat sandstone, until its form
becomes perfectly symmetrical (see Plate LII). Thus a number of flat, circular discs,
polished all round and perforated in the middle, are produced. The breaking and the
drilling, like the diving are done exclusively by men. The polishing is as a rule
woman’s work.

Plate LI
Working the Kaloma Shell (III.)

By means of a pump drill, a hole is bored in each disc. (See Div. III.)

Plate LII
Working the Kaloma Shell (IV.)

The shell discs, flat and perforated, but of irregular contour still,
are now threaded on to a thin, tough stick, and in this form they
are ground on a flat sandstone till the roll is cylindrical, that is,
each disc is a perfect circle. (See Div. III.)

This technology is associated with an interesting sociological relation between the


maker and the man for whom the article is made. As has been stated in Chapter II,
one of the main features of the Trobriand organisation consists of the mutual duties
between a man and his wife’s maternal kinsmen. They have to supply him regularly
with yams at harvest time, while he gives them the present of a valuable now and
then. The manufacture of kaloma valuables in Sinaketa is very often associated with
this relationship. The Sinaketan manufacturer makes his kutadababile (necklace of
large beads) for one of his relatives-in-law, while this latter pays him in food. In
accordance with this custom, it happens very frequently that a Sinaketan man
marries a woman from one of the agricultural inland villages, or even a woman of
Kiriwina. Of course, if he has no relatives-in-law in one of these villages, he will
have friends or distant relatives, and he will make the string for one or the other of
them. Or else he will produce one for himself, and launch it into the Kula. But the
most typical and interesting case is, when the necklace is produced to order for a
man who repays it according to a remarkable economic system, a system similar to
the payments in instalments, which I have mentioned with regard to canoe making. I
shall give here, following closely the native text, a translation of an account of the
payments for kaloma making.
Account of the Kaloma Making
Supposing some man from inland lives in Kiriwina or in Luba or in one of the villages
nearby; he wants a katudababile. He would request an expert fisherman who knows how to
dive for kaloma. This man agrees; he dives, he dives … till it is sufficient; his vataga
(large folding basket) is already full, this man (the inlander) hears the rumour; he, the
master of the kaloma (that is, the man for whom the necklace will be made) says: “Good! I
shall just have a look!” He would come, he would see, he would not give any vakapula
payment. He (here the Sinaketan diver is meant) would say: “Go, tomorrow, I shall break
the shell, come here, give me vakapula.” Next day, he (the inlander) would cook food, he
would bring, he would give vakapula; he (the diver) would break the shell. Next day, the
same. He (the inlander) would give the vakapula, he (the diver) would break the shell.
Supposing the breaking is already finished, he (the diver) would say: “Good! already the
breaking is finished, I shall polish.” Next day, he (the inlander) would cook food, would
bring bananas, coco-nut, betel-nut, sugar cane, would give it as vakapula; this man (the
diver) polishes. The polishing already finished, he would speak: “Good! To-morrow I shall
drill.” This man (the inlander) would bring food, bananas, coco-nuts, sugar cane, he would
give it as vakapula: it would be abundant, for soon already the necklace will be finished.
The same, he would give a big vakapula on the occasion of the rounding up of the
cylinder, for soon everything will be finished. When finished, we thread it on a string, we
wash it. (Note the change from the third singular into the first plural). We give it to our
wife, we blow the conch shell; she would go, she would carry his valuable to this man, our
relative-in-law. Next day, he would yomelu; he would catch a pig, he would break off a
bunch of betel-nut, he would cut sugar cane, bananas, he would fill the baskets with food,
and spike the coco-nut on a multi-forked piece of wood. By-and-by he would bring it. Our
house would be filled up. Later on we would make a distribution of the bananas, of the
sugar cane, of the betel-nut. We give it to our helpers. We sit, we sit (i.e., we wait); at
harvest time he brings yams, he karibudaboda (he gives the payment of that name), the
necklace. He would bring the food and fill out our yam house.

This narrative, like many pieces of native information, needs certain corrections of
perspective. In the first place, events here succeed one another with a rapidity quite
foreign to the extremely leisurely way in which natives usually accomplish such a
lengthy process as the making of a katudababile. The amount of food which, in the
usual manner, is enumerated over and over again in this narrative would probably
not be exaggerated, for—such is native economy—a man who makes a necklace to
order would get about twice as much or even more for it than it would fetch in any
other transaction. On the other hand, it must be remembered that what is represented
here as the final payment, the karibudaboda, is nothing else but the normal filling
up of the yam house, always done by a man’s relations-in-law. None the less, in a
year in which a katudababile would be made, the ordinary yearly harvest gift would
be styled the ‘karibudaboda payment for the necklace.’ The giving of the necklace
to the wife, who afterwards carries it to her brother or kinsman, is also characteristic
of the relation between relatives-in-law.

In Sinaketa and Vakuta only the necklaces made of bigger shell and tapering
towards the end are made. The real Kula article, in which the discs are much
thinner, smaller in diameter and even in size from one end of the necklace to the
other, these were introduced into the Kula at other points, and I shall speak about
this subject in one of the following chapters (Chapter XXI), where the other
branches of the Kula are described.

IV

Now, having come to an end of this digression on kaloma, let us return for another
short while to our Sinaketan party, whom we have left on the Lagoon of Sanaroa.
Having obtained a sufficient amount of the shells, they set sail, and re-visiting
Tewara and Gumasila, stopping perhaps for a night on one of the sandbanks of
Pilolu, they arrive at last in their home Lagoon. But before rejoining their people in
their villages, they stop for the last halt on Muwa. Here they make what is called
tanarere, a comparison and display of the valuables obtained on this trip. From each
canoe, a mat or two are spread on the sand beach, and the men put their necklaces
on the mat. Thus a long row of valuables lies on the beach, and the members of the
expedition walk up and down, admire, and count them. The chiefs would, of course,
have always the greatest haul, more especially the one who has been the
toli’uvalaku on that expedition.

After this is over, they return to the village. Each canoe blows its conch shell, a blast
for each valuable that it contains. When a canoe has obtained no vaygu’a at all, this
means great shame and distress for its members, and especially for the toliwaga.
Such a canoe is said to bisikureya, which means literally ‘to keep a fast.’

On the beach all the villagers are astir. The women, who have put on their new grass
petticoats (sevata’i) specially made for this occasion, enter the water and approach
the canoes to unload them. No special greetings pass between them and their
husbands. They are interested in the food brought from Dobu, more especially in the
sago.
People from other villages assemble also in great numbers to greet the incoming
party. Those who have supplied their friends or relatives with provisions for their
journey, receive now sago, betel-nuts and coco-nuts in repayment. Some of the
welcoming crowd have come in order to make Kula. Even from the distant districts
of Luba and Kiriwina natives will travel to Sinaketa, having a fair idea of the date of
the arrival of the Kula party from Dobu. The expedition will be talked over, the
yield counted, the recent history of the important valuables described. But this stage
leads us already into the subject of inland Kula, which will form the subject of one
of the following chapters.

You might also like