TypeScript Handbook TypeScript 4 8 Typescriptlang Org download
TypeScript Handbook TypeScript 4 8 Typescriptlang Org download
https://ebookmeta.com/product/typescript-handbook-
typescript-4-8-typescriptlang-org/
https://ebookmeta.com/product/typescript-handbook-
typescript-4-8-typescriptlang-org-2/
https://ebookmeta.com/product/typescript-handbook-
typescript-4-7-typescriptlang-org/
https://ebookmeta.com/product/essential-typescript-4-2nd-edition-
adam-freeman/
https://ebookmeta.com/product/practicing-forgiveness-a-path-
toward-healing-1st-edition-richard-s-balkin/
Alpha Geek 18 0 Maverick 1st Edition Milly Taiden
https://ebookmeta.com/product/alpha-geek-18-0-maverick-1st-
edition-milly-taiden/
https://ebookmeta.com/product/the-internet-of-medical-things-
iomt-healthcare-transformation-1st-edition-r-j-hemalatha/
https://ebookmeta.com/product/the-interview-book-how-to-prepare-
and-perform-at-your-best-in-any-interview-3rd-edition-james-
innes/
https://ebookmeta.com/product/scientific-american-mind-various/
https://ebookmeta.com/product/virulent-zones-animal-disease-and-
global-health-at-china-s-pandemic-epicenter-1st-edition-lyle-
fearnley/
The Anthropocene Debate and Political Science 1st
Edition Thomas Hickmann (Editor)
https://ebookmeta.com/product/the-anthropocene-debate-and-
political-science-1st-edition-thomas-hickmann-editor/
This copy of the TypeScript handbook was
created on Monday, August 29, 2022 against
commit 9e3487 with TypeScript 4.8.
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:
Another Random Scribd Document
with Unrelated Content
Fig. 5. and Fig. 6.
Here is a toy I happened to see the other day, which will, I think,
serve to illustrate our subject very well. That toy ought to lie
something in this manner (fig. 5); and would do so if it were uniform
in substance. But you see it does not; it will get up again. And now
philosophy comes to our aid; and I am perfectly sure, without
looking inside the figure, that there is some arrangement by which
the centre of gravity is at the lowest point when the image is
standing upright; and we may be certain, when I am tilting it over
(see fig. 6), that I am lifting up the centre of gravity (a), and raising
it from the earth. All this is effected by putting a piece of lead inside
the lower part of the image, and making the base of large curvature;
and there you have the whole secret. But what will happen if I try to
make the figure stand upon a sharp point? You observe, I must get
that point exactly under the centre of gravity, or it will fall over thus
[endeavouring unsuccessfully to balance it]; and this you see is a
difficult matter—I cannot make it stand steadily. But if I embarrass
this poor old lady with a world of trouble, and hang this wire with
bullets at each end about her neck, it is very evident that, owing to
there being those balls of lead hanging down on either side, in
addition to the lead inside, I have lowered the centre of gravity, and
now she will stand upon this point (fig. 7); and what is more, she
proves the truth of our philosophy by standing sideways.
Fig. 7.
Fig. 8.
Fig. 9.
Again, if you are really so inclined (and I do hope all of you are), you
will find a great deal of philosophy in this [holding up a cork and a
pointed thin stick about a foot long]. Do not refer to your toy-books,
and say you have seen that before. Answer me rather, if I ask you
have you understood it before? It is an experiment which appeared
very wonderful to me when I was a boy; I used to take a piece of
cork (and I remember, I thought at first that it was very important
that it should be cut out in the shape of a man; but by degrees I got
rid of that idea), and the problem was to balance it on the point of a
stick. Now, you will see I have only to place two sharp-pointed sticks
one on each side, and give it wings, thus, and you will find this
beautiful condition fulfilled.
Fig. 10.
Fig. 11.
I have here (fig. 11) a lamp a, shining most intensely upon this disc,
b, c, d; and this light acts as a sun by which I can get a shadow from
this little screen, b f (merely a square piece of card), which, as you
know, when I place it close to the large screen, just shadows as
much of it as is exactly equal to its own size. But now let me take
this card e, which is equal to the other one in size, and place it
midway between the lamp and the screen: now look at the size of
the shadow b d—it is four times the original size. Here, then, comes
the “inverse square of the distance.” This distance, a e, is one, and
that distance, a b, is two; but that size e being one, this size b d of
shadow is four instead of two, which is the square of the distance;
and, if I put the screen at one-third of the distance from the lamp,
the shadow on the large screen would be nine times the size. Again,
if I hold this screen here, at B F, a certain amount of light falls on it;
and if I hold it nearer the lamp at e, more light shines upon it. And
you see at once how much—exactly the quantity which I have shut
off from the part of this screen, b d, now in shadow; moreover, you
see that if I put a single screen here, at g, by the side of the
shadow, it can only receive one-fourth of the proportion of light
which is obstructed. That, then, is what is meant by the inverse of
the square of the distance. This screen e is the brightest, because it
is the nearest; and there is the whole secret of this curious
expression, inversely as the square of the distance. Now, if you
cannot perfectly recollect this when you go home, get a candle and
throw a shadow of something—your profile, if you like—on the wall,
and then recede or advance, and you will find that your shadow is
exactly in proportion to the square of the distance you are off the
wall; and then if you consider how much light shines on you at one
distance, and how much at another, you get the inverse accordingly.
So it is as regards the attraction of these two balls—they attract
according to the square of the distance, inversely. I want you to try
and remember these words, and then you will be able to go into all
the calculations of astronomers as to the planets and other bodies,
and tell why they move so fast, and why they go round the sun
without falling into it, and be prepared to enter upon many other
interesting inquiries of the like nature.
Let us now leave this subject which I have written upon the board
under the word Force—Gravitation—and go a step further. All bodies
attract each other at sensible distances. I shewed you the electric
attraction on the last occasion (though I did not call it so); that
attracts at a distance: and in order to make our progress a little
more gradual, suppose I take a few iron particles [dropping some
small fragments of iron on the table]. There, I have already told you
that in all cases where bodies fall, it is the particles that are
attracted. You may consider these then as separate particles
magnified, so as to be evident to your sight; they are loose from
each other—they all gravitate—they all fall to the earth—for the
force of gravitation never fails. Now, I have here a centre of power
which I will not name at present, and when these particles are
placed upon it, see what an attraction they have for each other.
Fig. 12.
Here I have an arch of iron filings (fig. 12) regularly built up like an
iron bridge, because I have put them within a sphere of action which
will cause them to attract each other. See!—I could let a mouse run
through it, and yet if I try to do the same thing with them here [on
the table], they do not attract each other at all. It is that [the
magnet] which makes them hold together. Now, just as these iron
particles hold together in the form of an elliptical bridge, so do the
different particles of iron which constitute this nail hold together and
make it one. And here is a bar of iron—why, it is only because the
different parts of this iron are so wrought as to keep close together
by the attraction between the particles that it is held together in one
mass. It is kept together, in fact, merely by the attraction of one
particle to another, and that is the point I want now to illustrate. If I
take a piece of flint and strike it with a hammer, and break it thus
[breaking off a piece of the flint], I have done nothing more than
separate the particles which compose these two pieces so far apart,
that their attraction is too weak to cause them to hold together, and
it is only for that reason that there are now two pieces in the place
of one. I will shew you an experiment to prove that this attraction
does still exist in those particles, for here is a piece of glass (for
what was true of the flint and the bar of iron is true of the piece of
glass, and is true of every other solid—they are all held together in
the lump by the attraction between their parts), and I can shew you
the attraction between its separate particles; for if I take these
portions of glass, which I have reduced to very fine powder, you see
that I can actually build them up into a solid wall by pressure
between two flat surfaces. The power which I thus have of building
up this wall is due to the attraction of the particles, forming as it
were the cement which holds them together; and so in this case,
where I have taken no very great pains to bring the particles
together, you see perhaps a couple of ounces of finely-pounded
glass standing as an upright wall. Is not this attraction most
wonderful? That bar of iron one inch square has such power of
attraction in its particles—giving to it such strength—that it will hold
up twenty tons weight before the little set of particles in the small
space, equal to one division across which it can be pulled apart, will
separate. In this manner suspension bridges and chains are held
together by the attraction of their particles; and I am going to make
an experiment which will shew how strong is this attraction of the
particles. [The Lecturer here placed his foot on a loop of wire
fastened to a support above, and swung with his whole weight
resting upon it for some moments.] You see while hanging here all
my weight is supported by these little particles of the wire, just as in
pantomimes they sometimes suspend gentlemen and damsels.
How can we make this attraction of the particles a little more
simple? There are many things which if brought together properly
will shew this attraction. Here is a boy’s experiment (and I like a
boy’s experiment). Get a tobacco-pipe, fill it with lead, melt it, and
then pour it out upon a stone, and thus get a clean piece of lead
(this is a better plan than scraping it—scraping alters the condition
of the surface of the lead). I have here some pieces of lead which I
melted this morning for the sake of making them clean. Now these
pieces of lead hang together by the attraction of their particles; and
if I press these two separate pieces close together, so as to bring
their particles within the sphere of attraction, you will see how soon
they become one. I have merely to give them a good squeeze, and
draw the upper piece slightly round at the same time, and here they
are as one, and all the bending and twisting I can give them will not
separate them again: I have joined the lead together, not with
solder, but simply by means of the attraction of the particles.
This, however, is not the best way of bringing those particles
together—we have many better plans than that; and I will shew you
one that will do very well for juvenile experiments. There is some
alum crystallised very beautifully by nature (for all things are far
more beautiful in their natural than their artificial form), and here I
have some of the same alum broken into fine powder. In it I have
destroyed that force of which I have placed the name on this board
—Cohesion, or the attraction exerted between the particles of bodies
to hold them together. Now I am going to shew you that if we take
this powdered alum and some hot water, and mix them together, I
shall dissolve the alum—all the particles will be separated by the
water far more completely than they are here in the powder; but
then, being in the water, they will have the opportunity as it cools
(for that is the condition which favours their coalescence) of uniting
together again and forming one mass.7
Now, having brought the alum into solution, I will pour it into this
glass basin, and you will, to-morrow, find that those particles of
alum which I have put into the water, and so separated that they are
no longer solid, will, as the water cools, come together and cohere,
and by to-morrow morning we shall have a great deal of the alum
crystallised out—that is to say, come back to the solid form. [The
Lecturer here poured a little of the hot solution of alum into the
glass dish, and when the latter had thus been made warm, the
remainder of the solution was added.] I am now doing that which I
advise you to do if you use a glass vessel, namely, warming it slowly
and gradually; and in repeating this experiment, do as I do—pour
the liquid out gently, leaving all the dirt behind in the basin: and
remember that the more carefully and quietly you make this
experiment at home, the better the crystals. To-morrow you will see
the particles of alum drawn together; and if I put two pieces of coke
in some part of the solution (the coke ought first to be washed very
clean, and dried), you will find to-morrow that we shall have a
beautiful crystallisation over the coke, making it exactly resemble a
natural mineral.
Now, how curiously our ideas expand by watching these conditions
of the attraction of cohesion!—how many new phenomena it gives
us beyond those of the attraction of gravitation! See how it gives us
great strength. The things we deal with in building up the structures
on the earth are of strength (we use iron, stone, and other things of
great strength); and only think that all those structures you have
about you—think of the “Great Eastern,” if you please, which is of
such size and power as to be almost more than man can manage—
are the result of this power of cohesion and attraction.
I have here a body in which I believe you will see a change taking
place in its condition of cohesion at the moment it is made. It is at
first yellow, it then becomes a fine crimson red. Just watch when I
pour these two liquids together—both colourless as water. [The
Lecturer here mixed together solutions of perchloride of mercury and
iodide of potassium, when a yellow precipitate of biniodide of
mercury fell down, which almost immediately became crimson red.]
Now, there is a substance which is very beautiful, but see how it is
changing colour. It was reddish-yellow at first, but it has now
become red.8 I have previously prepared a little of this red
substance, which you see formed in the liquid, and have put some of
it upon paper. [Exhibiting several sheets of paper coated with scarlet
biniodide of mercury.9] There it is—the same substance spread upon
paper; and there, too, is the same substance; and here is some
more of it [exhibiting a piece of paper as large as the other sheets,
but having only very little red colour on it, the greater part being
yellow], a little more of it, you will say. Do not be mistaken; there is
as much upon the surface of one of these pieces of paper as upon
the other. What you see yellow is the same thing as the red body,
only the attraction of cohesion is in a certain degree changed; for I
will take this red body, and apply heat to it (you may perhaps see a
little smoke arise, but that is of no consequence), and if you look at
it, it will first of all darken—but see, how it is becoming yellow. I
have now made it all yellow, and what is more, it will remain so; but
if I take any hard substance, and rub the yellow part with it, it will
immediately go back again to the red condition. [Exhibiting the
experiment.] There it is. You see the red is not put back, but brought
back by the change in the substance. Now [warming it over the spirit
lamp] here it is becoming yellow again, and that is all because its
attraction of cohesion is changed. And what will you say to me when
I tell you that this piece of common charcoal is just the same thing,
only differently calesced, as the diamonds which you wear? (I have
put a specimen outside of a piece of straw which was charred in a
particular way—it is just like black lead.) Now, this charred straw,
this charcoal, and these diamonds, are all of them the same
substance, changed but in their properties as respects the force of
cohesion.
Here is a piece of glass [producing a piece of plate-glass about two
inches square]—(I shall want this afterwards to look to and examine
its internal condition)—and here is some of the same sort of glass
differing only in its power of cohesion, because while yet melted it
has been dropped into cold water [exhibiting a “Prince Rupert’s
drop”.10 (fig. 13)]; and if I take one of these little tear-like pieces
and break off ever so little from the point, the whole will at once
burst and fall to pieces. I will now break off a piece of this. [The
Lecturer nipped off a small piece from the end of one of the Rupert’s
drops, whereupon the whole immediately fell to pieces.] There! you
see the solid glass has suddenly become powder—and more than
that, it has knocked a hole in the glass vessel in which it was held. I
can shew the effect better in this bottle of water; and it is very likely
the whole bottle will go. [A 6-oz. vial was filled with water, and a
Rupert’s drop placed in it, with the point of the tail just projecting
out; upon breaking the tip off, the drop burst, and the shock being
transmitted through the water to the sides of the bottle, shattered
the latter to pieces.]
Here is another form of the same kind of experiment. I have here
some more glass which has not been annealed [showing some thick
glass vessels11 (fig. 14)], and if I take one of these glass vessels and
drop a piece of pounded glass into it (or I will take some of these
small pieces of rock crystal—they have the advantage of being
harder than glass), and so make the least scratch upon the inside,
the whole bottle will break to pieces,—it cannot hold together. [The
Lecturer here dropped a small fragment of rock crystal into one of
these glass vessels, when the bottom immediately came out and fell
upon the plate.] There! it goes through, just as it would through a
sieve.
Now, I have shewn you these things for the purpose of bringing your
minds to see that bodies are not merely held together by this power
of cohesion, but that they are held together in very curious ways.
And suppose I take some things that are held together by this force,
and examine them more minutely. I will first take a bit of glass, and
if I give it a blow with a hammer, I shall just break it to pieces. You
saw how it was in the case of the flint when I broke the piece off; a
piece of a similar kind would come off, just as you would expect; and
if I were to break it up still more, it would be as you have seen,
simply a collection of small particles of no definite shape or form.
But supposing I take some other thing, this stone for instance (fig.
15) [taking a piece of mica12], and if I hammer this stone, I may
batter it a great deal before I can break it up. I may even bend it
without breaking it; that is to say, I may bend it in one particular
direction without breaking it much, although I feel in my hands that
I am doing it some injury. But now, if I take it by the edges, I find
that it breaks up into leaf after leaf in a most extraordinary manner.
Why should it break up like that? Not because all stones do, or all
crystals; for there is some salt (fig. 16)—you know what common
salt is13: here is a piece of this salt which by natural circumstances
has had its particles so brought together that they have been
allowed free opportunity of combining or coalescing; and you shall
see what happens if I take this piece of salt and break it. It does not
break as flint did, or as the mica did, but with a clean sharp angle
and exact surfaces, beautiful and glittering as diamonds [breaking it
by gentle blows with a hammer]; there is a square prism which I
may break up into a square cube. You see these fragments are all
square—one side may be longer than the other, but they will only
split up so as to form square or oblong pieces with cubical sides.
Now, I go a little further, and I find another stone (fig. 17) [Iceland,
or calc-spar]14, which I may break in a similar way, but not with the
same result. Here is a piece which I have broken off, and you see
there are plain surfaces perfectly regular with respect to each other;
but it is not cubical—it is what we call a rhomboid. It still breaks in
three directions most beautifully and regularly, with polished
surfaces, but with sloping sides, not like the salt. Why not? It is very
manifest that this is owing to the attraction of the particles, one for
the other, being less in the direction in which they give way than in
other directions. I have on the table before me a number of little bits
of calcareous spar, and I recommend each of you to take a piece
home, and then you can take a knife and try to divide it in the
direction of any of the surfaces already existing. You will be able to
do it at once; but if you try to cut it across the crystals, you cannot—
by hammering, you may bruise and break it up—but you can only
divide it into these beautiful little rhomboids.
Now I want you to understand a little more how this is—and for this
purpose I am going to use the electric light again. You see, we
cannot look into the middle of a body like this piece of glass. We
perceive the outside form, and the inside form, and we look through
it; but we cannot well find out how these forms become so: and I
want you, therefore, to take a lesson in the way in which we use a
ray of light for the purpose of seeing what is in the interior of
bodies. Light is a thing which is, so to say, attracted by every
substance that gravitates (and we do not know anything that does
not). All matter affects light more or less by what we may consider
as a kind of attraction, and I have arranged (fig. 18) a very simple
experiment upon the floor of the room for the purpose of illustrating
this. I have put into that basin a few things which those who are in
the body of the theatre will not be able to see, and I am going to
make use of this power, which matter possesses, of attracting a ray
of light. If Mr. Anderson pours some water, gently and steadily, into
the basin, the water will attract the rays of light downwards, and the
piece of silver and the sealing-wax will appear to rise up into the
sight of those who were before not high enough to see over the side
of the basin to its bottom. [Mr. Anderson here poured water into the
basin, and upon the Lecturer asking whether any body could see the
silver and sealing-wax, he was answered by a general affirmative.]
Now, I suppose that everybody can see that they are not at all
disturbed, whilst from the way they appear to have risen up, you
would imagine the bottom of the basin and the articles in it were
two inches thick, although they are only one of our small silver
dishes and a piece of sealing-wax which I have put there. The light
which now goes to you from that piece of silver was obstructed by
the edge of the basin, when there was no water there, and you were
unable to see anything of it; but when we poured in water, the rays
were attracted down by it, over the edge of the basin, and you were
thus enabled to see the articles at the bottom.
Fig. 18.
Fig. 19.
I have shewn you this experiment first, so that you might
understand how glass attracts light, and might then see how other
substances, like rock-salt and calcareous spar, mica, and other
stones, would affect the light; and, if Dr. Tyndall will be good enough
to let us use his light again, we will first of all shew you how it may
be bent by a piece of glass (fig. 19). [The electric lamp was again lit,
and the beam of parallel rays of light which it emitted was bent
about and decomposed by means of the prism.] Now, here you see,
if I send the light through this piece of plain glass, a, it goes straight
through, without being bent, unless the glass be held obliquely, and
then the phenomenon becomes more complicated; but if I take this
piece of glass, b [a prism], you see it will shew a very different
effect. It no longer goes to that wall, but it is bent to this screen, c;
and how much more beautiful it is now [throwing the prismatic
spectrum on the screen]. This ray of light is bent out of its course by
the attraction of the glass upon it. And you see I can turn and twist
the rays to and fro, in different parts of the room, just as I please.
Now it goes there, now here. [The Lecturer projected the prismatic
spectrum about the theatre.] Here I have the rays once more bent
on to the screen, and you see how wonderfully and beautifully that
piece of glass not only bends the light by virtue of its attraction, but
actually splits it up into different colours. Now, I want you to
understand that this piece of glass [the prism] being perfectly
uniform in its internal structure, tells us about the action of these
other bodies which are not uniform—which do not merely cohere,
but also have within them, in different parts, different degrees of
cohesion, and thus attract and bend the light with varying powers.
We will now let the light pass through one or two of these things
which I just now shewed you broke so curiously; and, first of all, I
will take a piece of mica. Here, you see, is our ray of light. We have
first to make it what we call polarised; but about that you need not
trouble yourselves—it is only to make our illustration more clear.
Here, then, we have our polarised ray of light, and I can so adjust it
as to make the screen upon which it is shining either light or dark,
although I have nothing in the course of this ray of light but what is
perfectly transparent [turning the analyser round]. I will now make it
so that it is quite dark; and we will, in the first instance, put a piece
of common glass into the polarised ray, so as to shew you that it
does not enable the light to get through. You see the screen remains
dark. The glass then, internally, has no effect upon the light. [The
glass was removed, and a piece of mica introduced.] Now, there is
the mica which we split up so curiously into leaf after leaf, and see
how that enables the light to pass through to the screen, and how,
as Dr. Tyndall turns it round in his hand, you have those different
colours, pink, and purple, and green, coming and going most
beautifully—not that the mica is more transparent than the glass,
but because of the different manner in which its particles are
arranged by the force of cohesion.
Fig. 20.
Now we will see how calcareous spar acts upon this light,—that
stone which split up into rhombs, and of which you are each of you
going to take a little piece home. [The mica was removed, and a
piece of calc-spar introduced at a.] See how that turns the light
round and round, and produces these rings and that black cross (fig.
20). Look at those colours—are they not most beautiful for you and
for me?—for I enjoy these things as much as you do. In what a
wonderful manner they open out to us the internal arrangement of
the particles of this calcareous spar by the force of cohesion.
And now I will shew you another experiment. Here is that piece of
glass which before had no action upon the light. You shall see what
it will do when we apply pressure to it. Here, then, we have our ray
of polarised light, and I will first of all shew you that the glass has
no effect upon it in its ordinary state,—when I place it in the course
of the light, the screen still remains dark. Now, Dr. Tyndall will press
that bit of glass between three little points, one point against two, so
as to bring a strain upon the parts, and you will see what a curious
effect that has. [Upon the screen two white dots gradually
appeared.] Ah! these points shew the position of the strain—in these
parts the force of cohesion is being exerted in a different degree to
what it is in the other parts, and hence it allows the light to pass
through. How beautiful that is—how it makes the light come through
some parts, and leaves it dark in others, and all because we weaken
the force of cohesion between particle and particle. Whether you
have this mechanical power of straining, or whether we take other
means, we get the same result; and, indeed, I will shew you by
another experiment that if we heat the glass in one part, it will alter
its internal structure, and produce a similar effect. Here is a piece of
common glass, and if I insert this in the path of the polarised ray, I
believe it will do nothing. There is the common glass [introducing it]
—no light passes through—the screen remains quite dark; but I am
going to warm this glass in the lamp, and you know yourselves that
when you pour warm water upon glass you put a strain upon it
sufficient to break it sometimes—something like there was in the
case of the Prince Rupert’s drops. [The glass was warmed in the
spirit-lamp, and again placed across the ray of light.] Now you see
how beautifully the light goes through those parts which are hot,
making dark and light lines just as the crystal did, and all because of
the alteration I have effected in its internal condition; for these dark
and light parts are a proof of the presence of forces acting and
dragging in different directions within the solid mass.
LECTURE III.
COHESION—CHEMICAL AFFINITY.
Fig. 21.
This experiment cannot, I think, fail to impress upon your minds the
fact, that whenever a solid body loses some of that force of
attraction by means of which it remains solid, heat is absorbed; and
if, on the other hand, we convert a liquid into a solid, e.g., water into
ice, a corresponding amount of heat is given out. I have an
experiment shewing this to be the case. Here (fig. 21) is a bulb, a,
filled with air, the tube from which dips into some coloured liquid in
the vessel b. And I dare say you know that if I put my hand on the
bulb a, and warm it, the coloured liquid which is now standing in the
tube at c will travel forward. Now we have discovered a means, by
great care and research into the properties of various bodies, of
preparing a solution of a salt15 which, if shaken or disturbed, will at
once become a solid; and as I explained to you just now (for what is
true of water is true of every other liquid), by reason of its becoming
solid, heat is evolved, and I can make this evident to you by pouring
it over this bulb;—there! it is becoming solid, and look at the
coloured liquid, how it is being driven down the tube, and how it is
bubbling out through the water at the end; and so we learn this
beautiful law of our philosophy, that whenever we diminish the
attraction of cohesion, we absorb heat—and whenever we increase
that attraction, heat is evolved. This, then, is a great step in
advance, for you have learned a great deal in addition to the mere
circumstance that particles attract each other. But you must not now
suppose that because they are liquid they have lost their attraction
of cohesion; for here is the fluid mercury, and if I pour it from one
vessel into another, I find that it will form a stream from the bottle
down to the glass—a continuous rod of fluid mercury, the particles of
which have attraction sufficient to make them hold together all the
way through the air down to the glass itself; and if I pour water
quietly from a jug, I can cause it to run in a continuous stream in
the same manner. Again, let me put a little water on this piece of
plate-glass, and then take another plate of glass and put it on the
water; there! the upper plate is quite free to move, gliding about on
the lower one from side to side; and yet, if I take hold of the upper
plate and lift it up straight, the cohesion is so great that the lower
one is held up by it. See how it runs about as I move the upper one!
and this is all owing to the strong attraction of the particles of the
water. Let me shew you another experiment. If I take a little soap
and water—not that the soap makes the particles of the water more
adhesive one for the other but it certainly has the power of
continuing in a better manner the attraction of the particles (and let
me advise you, when about to experiment with soap-bubbles, to
take care to have everything clean and soapy). I will now blow a
bubble; and that I may be able to talk and blow a bubble too, I will
take a plate with a little of the soapsuds in it, and will just soap the
edges of the pipe, and blow a bubble on to the plate. Now, there is
our bubble. Why does it hold together in this manner? Why, because
the water of which it is composed has an attraction of particle for
particle,—so great, indeed, that it gives to this bubble the very
power of an india-rubber ball; for you see, if I introduce one end of
this glass tube into the bubble, that it has the power of contracting
so powerfully as to force enough air through the tube to blow out a
light (fig. 22)—the light is blown out. And look! see how the bubble
is disappearing, see how it is getting smaller and smaller.
Fig. 22. and Fig. 23.