TypeScript Handbook TypeScript 4 7 Typescriptlang Org 2024 Scribd Download
TypeScript Handbook TypeScript 4 7 Typescriptlang Org 2024 Scribd Download
com
https://ebookmeta.com/product/typescript-handbook-
typescript-4-7-typescriptlang-org/
OR CLICK BUTTON
DOWNLOAD NOW
https://ebookmeta.com/product/typescript-handbook-
typescript-4-8-typescriptlang-org/
ebookmeta.com
https://ebookmeta.com/product/typescript-handbook-
typescript-4-8-typescriptlang-org-2/
ebookmeta.com
https://ebookmeta.com/product/essential-typescript-4-2nd-edition-adam-
freeman/
ebookmeta.com
https://ebookmeta.com/product/education-policy-research-
epistemological-and-theoretical-issues-1st-edition-mainardes/
ebookmeta.com
Reconceptualizing Schizophrenia The Phenomenology of
Urhomelessness 1st Edition Edited By Sarah R Kamens
https://ebookmeta.com/product/reconceptualizing-schizophrenia-the-
phenomenology-of-urhomelessness-1st-edition-edited-by-sarah-r-kamens/
ebookmeta.com
https://ebookmeta.com/product/the-cambridge-companion-to-rabindranath-
tagore-cambridge-companions-to-literature-sukanta-chaudhuri-editor/
ebookmeta.com
https://ebookmeta.com/product/an-introductory-course-to-philosophy-of-
language-ufuk-azen-baykent/
ebookmeta.com
https://ebookmeta.com/product/the-healing-energy-of-your-hands-
michael-bradford/
ebookmeta.com
https://ebookmeta.com/product/the-dynamics-of-right-wing-extremism-
within-german-society-1st-edition-oliver-decker/
ebookmeta.com
A Clinician's Guide to Statistics in Mental Health S.
Nassir Ghaemi
https://ebookmeta.com/product/a-clinicians-guide-to-statistics-in-
mental-health-s-nassir-ghaemi/
ebookmeta.com
This copy of the TypeScript handbook was
created on Friday, June 24, 2022 against commit
e538f6 with TypeScript 4.7.
Table of Contents
The most common kinds of errors that programmers write can be described as type errors: a
certain kind of value was used where a different kind of value was expected. This could be due to
simple typos, a failure to understand the API surface of a library, incorrect assumptions about
runtime behavior, or other errors. The goal of TypeScript is to be a static typechecker for JavaScript
programs - in other words, a tool that runs before your code runs (static) and ensures that the types
of the program are correct (typechecked).
If you are coming to TypeScript without a JavaScript background, with the intention of TypeScript
being your first language, we recommend you first start reading the documentation on either the
Microsoft Learn JavaScript tutorial or read JavaScript at the Mozilla Web Docs. If you have
experience in other languages, you should be able to pick up JavaScript syntax quite quickly by
reading the handbook.
The Handbook
You should expect each chapter or page to provide you with a strong understanding of the given
concepts. The TypeScript Handbook is not a complete language specification, but it is intended to
be a comprehensive guide to all of the language's features and behaviors.
A reader who completes the walkthrough should be able to:
In the interests of clarity and brevity, the main content of the Handbook will not explore every
edge case or minutiae of the features being covered. You can find more details on particular
concepts in the reference articles.
Reference Files
The reference section below the handbook in the navigation is built to provide a richer
understanding of how a particular part of TypeScript works. You can read it top-to-bottom, but
each section aims to provide a deeper explanation of a single concept - meaning there is no aim
for continuity.
Non-Goals
The Handbook is also intended to be a concise document that can be comfortably read in a few
hours. Certain topics won't be covered in order to keep things short.
Specifically, the Handbook does not fully introduce core JavaScript basics like functions, classes, and
closures. Where appropriate, we'll include links to background reading that you can use to read up
on those concepts.
The Handbook also isn't intended to be a replacement for a language specification. In some cases,
edge cases or formal descriptions of behavior will be skipped in favor of high-level, easier-to-
understand explanations. Instead, there are separate reference pages that more precisely and
formally describe many aspects of TypeScript's behavior. The reference pages are not intended for
readers unfamiliar with TypeScript, so they may use advanced terminology or reference topics you
haven't read about yet.
Finally, the Handbook won't cover how TypeScript interacts with other tools, except where
necessary. Topics like how to configure TypeScript with webpack, rollup, parcel, react, babel, closure,
lerna, rush, bazel, preact, vue, angular, svelte, jquery, yarn, or npm are out of scope - you can find
these resources elsewhere on the web.
Get Started
Before getting started with The Basics, we recommend reading one of the following introductory
pages. These introductions are intended to highlight key similarities and differences between
TypeScript and your favored programming language, and clear up common misconceptions
specific to those languages.
// Calling 'message'
message();
If we break this down, the first runnable line of code accesses a property called toLowerCase and
then calls it. The second one tries to call message directly.
But assuming we don't know the value of message - and that's pretty common - we can't reliably
say what results we'll get from trying to run any of this code. The behavior of each operation
depends entirely on what value we had in the first place.
Is message callable?
The answers to these questions are usually things we keep in our heads when we write JavaScript,
and we have to hope we got all the details right.
As you can probably guess, if we try to run message.toLowerCase() , we'll get the same string
only in lower-case.
What about that second line of code? If you're familiar with JavaScript, you'll know this fails with an
exception:
When we run our code, the way that our JavaScript runtime chooses what to do is by figuring out
the type of the value - what sorts of behaviors and capabilities it has. That's part of what that
TypeError is alluding to - it's saying that the string "Hello World!" cannot be called as a
function.
For some values, such as the primitives string and number , we can identify their type at runtime
using the typeof operator. But for other things like functions, there's no corresponding runtime
mechanism to identify their types. For example, consider this function:
function fn(x) {
return x.flip();
}
We can observe by reading the code that this function will only work if given an object with a
callable flip property, but JavaScript doesn't surface this information in a way that we can check
while the code is running. The only way in pure JavaScript to tell what fn does with a particular
value is to call it and see what happens. This kind of behavior makes it hard to predict what code
will do before it runs, which means it's harder to know what your code is going to do while you're
writing it.
Seen in this way, a type is the concept of describing which values can be passed to fn and which
will crash. JavaScript only truly provides dynamic typing - running the code to see what happens.
The alternative is to use a static type system to make predictions about what code is expected
before it runs.
Static type-checking
Think back to that TypeError we got earlier from trying to call a string as a function. Most
people don't like to get any sorts of errors when running their code - those are considered bugs!
And when we write new code, we try our best to avoid introducing new bugs.
If we add just a bit of code, save our file, re-run the code, and immediately see the error, we might
be able to isolate the problem quickly; but that's not always the case. We might not have tested the
feature thoroughly enough, so we might never actually run into a potential error that would be
thrown! Or if we were lucky enough to witness the error, we might have ended up doing large
refactorings and adding a lot of different code that we're forced to dig through.
Ideally, we could have a tool that helps us find these bugs before our code runs. That's what a static
type-checker like TypeScript does. Static types systems describe the shapes and behaviors of what
our values will be when we run our programs. A type-checker like TypeScript uses that information
and tells us when things might be going off the rails.
message();
This
This expression
expression is
is not
not callable.
callable.
Type
Type 'String'
'String' has
has no
no call
call signatures.
signatures.
Running that last sample with TypeScript will give us an error message before we run the code in
the first place.
Non-exception Failures
So far we've been discussing certain things like runtime errors - cases where the JavaScript runtime
tells us that it thinks something is nonsensical. Those cases come up because the ECMAScript
specification has explicit instructions on how the language should behave when it runs into
something unexpected.
For example, the specification says that trying to call something that isn't callable should throw an
error. Maybe that sounds like "obvious behavior", but you could imagine that accessing a property
that doesn't exist on an object should throw an error too. Instead, JavaScript gives us different
behavior and returns the value undefined :
const user = {
name: "Daniel",
age: 26,
};
const user = {
name: "Daniel",
age: 26,
};
user.location;
Property
Property 'location'
'location' does
does not
not exist
exist on
on type
type '{
'{ name:
name: string;
string; age:
age: number;
number;
}'. }'.
While sometimes that implies a trade-off in what you can express, the intent is to catch legitimate
bugs in our programs. And TypeScript catches a lot of legitimate bugs.
uncalled functions,
function flipCoin() {
// Meant to be Math.random()
return Math.random < 0.5;
Operator
Operator '<'
'<' cannot
cannot be
be applied
applied to
to types
types '()
'() =>
=> number'
number' and
and 'number'.
'number'.
This
This condition
condition will
will always
always return
return 'false'
'false' since
since the
the types
types '"a"'
'"a"' and
and '"b"'
'"b"'
have nohave
overlap.
no overlap.
// Oops, unreachable
}
The type-checker has information to check things like whether we're accessing the right properties
on variables and other properties. Once it has that information, it can also start suggesting which
properties you might want to use.
That means TypeScript can be leveraged for editing code too, and the core type-checker can
provide error messages and code completion as you type in the editor. That's part of what people
often refer to when they talk about tooling in TypeScript.
sendfile
app.listen(3000);
sendFile
TypeScript takes tooling seriously, and that goes beyond completions and errors as you type. An
editor that supports TypeScript can deliver "quick fixes" to automatically fix errors, refactorings to
easily re-organize code, and useful navigation features for jumping to definitions of a variable, or
finding all references to a given variable. All of this is built on top of the type-checker and is fully
cross-platform, so it's likely that your favorite editor has TypeScript support available.
tsc , the TypeScript compiler
We've been talking about type-checking, but we haven't yet used our type-checker. Let's get
acquainted with our new friend tsc , the TypeScript compiler. First we'll need to grab it via npm.
This installs the TypeScript Compiler tsc globally. You can use npx or similar tools if you'd prefer to
run tsc from a local node_modules package instead.
Now let's move to an empty folder and try writing our first TypeScript program: hello.ts :
Notice there are no frills here; this "hello world" program looks identical to what you'd write for a
"hello world" program in JavaScript. And now let's type-check it by running the command tsc
which was installed for us by the typescript package.
tsc hello.ts
Tada!
Wait, "tada" what exactly? We ran tsc and nothing happened! Well, there were no type errors, so
we didn't get any output in our console since there was nothing to report.
But check again - we got some file output instead. If we look in our current directory, we'll see a
hello.js file next to hello.ts . That's the output from our hello.ts file after tsc compiles
or transforms it into a plain JavaScript file. And if we check the contents, we'll see what TypeScript
spits out after it processes a .ts file:
greet("Brendan");
If we run tsc hello.ts again, notice that we get an error on the command line!
TypeScript is telling us we forgot to pass an argument to the greet function, and rightfully so. So
far we've only written standard JavaScript, and yet type-checking was still able to find problems
with our code. Thanks TypeScript!
To reiterate from earlier, type-checking code limits the sorts of programs you can run, and so there's
a tradeoff on what sorts of things a type-checker finds acceptable. Most of the time that's okay, but
there are scenarios where those checks get in the way. For example, imagine yourself migrating
JavaScript code over to TypeScript and introducing type-checking errors. Eventually you'll get
around to cleaning things up for the type-checker, but that original JavaScript code was already
working! Why should converting it over to TypeScript stop you from running it?
So TypeScript doesn't get in your way. Of course, over time, you may want to be a bit more
defensive against mistakes, and make TypeScript act a bit more strictly. In that case, you can use the
noEmitOnError compiler option. Try changing your hello.ts file and running tsc with that
flag:
Explicit Types
Up until now, we haven't told TypeScript what person or date are. Let's edit the code to tell
TypeScript that person is a string , and that date should be a Date object. We'll also use the
toDateString() method on date .
What we did was add type annotations on person and date to describe what types of values
greet can be called with. You can read that signature as " greet takes a person of type
string , and a date of type Date ".
With this, TypeScript can tell us about other cases where greet might have been called incorrectly.
For example...
greet("Maddison", Date());
Argument
Argument of
of type
type 'string'
'string' is
is not
not assignable
assignable to
to parameter
parameter of
of type
type 'Date'.
'Date'.
Keep in mind, we don't always have to write explicit type annotations. In many cases, TypeScript can
even just infer (or "figure out") the types for us even if we omit them.
Even though we didn't tell TypeScript that msg had the type string it was able to figure that out.
That's a feature, and it's best not to add annotations when the type system would end up inferring
the same type anyway.
Note: The message bubble inside the previous code sample is what your editor would show if you had
hovered over the word.
Erased Types
Let's take a look at what happens when we compile the above function greet with tsc to output
JavaScript:
"use strict";
function greet(person, date) {
console.log("Hello ".concat(person, ", today is ").concat(date.toDateS
}
greet("Maddison", new Date());
Notice two things here:
More on that second point later, but let's now focus on that first point. Type annotations aren't part
of JavaScript (or ECMAScript to be pedantic), so there really aren't any browsers or other runtimes
that can just run TypeScript unmodified. That's why TypeScript needs a compiler in the first place -
it needs some way to strip out or transform any TypeScript-specific code so that you can run it.
Most TypeScript-specific code gets erased away, and likewise, here our type annotations were
completely erased.
Remember: Type annotations never change the runtime behavior of your program.
Downleveling
One other difference from the above was that our template string was rewritten from
to
Template strings are a feature from a version of ECMAScript called ECMAScript 2015 (a.k.a.
ECMAScript 6, ES2015, ES6, etc. - don't ask). TypeScript has the ability to rewrite code from newer
versions of ECMAScript to older ones such as ECMAScript 3 or ECMAScript 5 (a.k.a. ES3 and ES5).
This process of moving from a newer or "higher" version of ECMAScript down to an older or
"lower" one is sometimes called downleveling.
By default TypeScript targets ES3, an extremely old version of ECMAScript. We could have chosen
something a little bit more recent by using the target option. Running with --target es2015
changes TypeScript to target ECMAScript 2015, meaning code should be able to run wherever
ECMAScript 2015 is supported. So running tsc --target es2015 hello.ts gives us the
following output:
Other documents randomly have
different content
The Project Gutenberg eBook of Old Indian
trails
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with
this ebook or online at www.gutenberg.org. If you are not located
in the United States, you will have to check the laws of the
country where you are located before using this eBook.
Language: English
[Contents]
[Contents]
sunset from lookout butte (page 197)
[Contents]
OLD INDIAN TRAILS
BY
WALTER McCLINTOCK, M.A.
WITH ILLUSTRATIONS
FROM PHOTOGRAPHS BY THE
AUTHOR
[Contents]
[Contents]
TO MY MOTHER
We made our last survey in the heavy forest on the western side of
the Rocky Mountains. Then Graves set out for Kalispell and
civilization; Pinchot, with Jack Munroe and our bear dogs, started
south for Fort Missoula; I was left alone with the Indian scout. [viii]
We crossed the mountains together and joined the tribal camp of the
Blackfoot Indians on the plains. There I met many of their leading
men; among them Chief Mad Wolf, who adopted me as his son, in
ceremonies lasting through two days, and made me a member of his
tribe.
But into the region where we wandered civilization came with its
automobile highways and great modern hotels. The old generation of
Indians have died and their children are civilized. The Blackfoot are no
longer nomads and hunters, following the great herds of buffalo and
other game; they till the soil and live in houses like white men. Their
ancient customs and tribal life have passed away forever.
W. McC. [ix]
[Contents]
CONTENTS
I. My Indian Guide 3
II. Crossing the Rocky Mountains 8
III. Our Camp near the Summit 15
IV. Home of the Scout 21
V. Stories by the Scout’s Mother-in-Law 32
VI. My Adoption by Mad Wolf 35
VII. Mad Wolf tells the Legend of the Beaver Bundle 42
VIII. I am given an Indian Name and made a Member of
the Blackfoot Tribe 54
IX. Home of Mad Wolf 68
X. Marriage Customs 80
XI. The Head-Chief and his Wife 85
XII. Legend of the Smoking Star 92
XIII. My Night Experience with a Grizzly Bear 100
XIV. Indian Summer 109
XV. A Frontier Dance 119
XVI. Hunting Rocky Mountain Goats 124
XVII. The Blizzard 130
XVIII. Snow-Bound 139
XIX. The Mad Indian 144
XX. Coming of the Chinook 149
XXI. Beginning of Spring 153
XXII. Our Camp in the Mountains [x] 158
XXIII. Our North Expedition 166
XXIV. Onesta and his Sacred Bear Spear 174
XXV. Camp of the Blood Indians 179
XXVI. Country of the North Piegans 184
XXVII. Camp of Brings-Down-the-Sun 191
XXVIII. Onesta gives his Crow Water Ceremony 199
XXIX. The Rival Medicine Men 206
XXX. Brings-Down-the-Sun tells about his Father 210
XXXI. Brings-Down-the-Sun tells about Men’s
Societies 219
XXXII. Brings-Down-the-Sun tells about the Birds and
the Stars 226
XXXIII. Legends of Star Boy and Scarface 232
XXXIV. Beginning of the Sun Dance 241
XXXV. Forming the Great Circle Camp 247
XXXVI. Life in the Circle Camp 253
XXXVII. Painted Tepees and Picture Writing 258
XXXVIII. A Native Doctor and his Patient 267
XXXIX. Dance of the Hair-Parters (Grass Dance) 274
XL. Society of Brave Dogs 284
XLI. A Medicine-Pipe Ceremony 289
XLII. A Sacred Ceremony in Mad Wolf’s Tepee 298
XLIII. The Tribal Dancing-Lodge 304
XLIV. End of the Sun Dance and Farewell of my Indian
Father 310
Appendix: Medicinal and Useful Plants of the
Blackfoot Indians 319
Index 327
[xi]
[Contents]
ILLUSTRATIONS
[1]
[3]
[Contents]
OLD INDIAN TRAILS
CHAPTER I