Instant Ebook Access, One Click Away – Begin at ebooknice.com (Ebook) Programming TypeScript: Making Your JavaScript Applications Scale by Boris Cherny https://ebooknice.com/product/programming-typescript-making- your-javascript-applications-scale-38567168 OR CLICK BUTTON DOWLOAD EBOOK Get Instant Ebook Downloads – Browse at https://ebooknice.com
Instant digital products (PDF, ePub, MOBI) ready for you Download now and discover formats that fit your needs... Start reading on any device today! (Ebook) Programming TypeScript: Making your JavaScript applications scale by Boris Cherny ISBN 9781492037651, 9781492037620, 1492037656, 1492037621 https://ebooknice.com/product/programming-typescript-making-your-javascript- applications-scale-33607784 ebooknice.com (Ebook) Programming TypeScript by Boris Cherny ISBN 9781492037651, 1492037656 https://ebooknice.com/product/programming-typescript-10479588 ebooknice.com (Ebook) Pro TypeScript: Application-Scale JavaScript Development by Steve Fenton ISBN 9781484232484, 9781484232491, 1484232488, 1484232496 https://ebooknice.com/product/pro-typescript-application-scale-javascript- development-6840582 ebooknice.com (Ebook) Pro TypeScript: application-scale javascript development by Fenton, Steve ISBN 9780932633422, 9781484232484, 9781484232491, 0932633420, 1484232488, 1484232496 https://ebooknice.com/product/pro-typescript-application-scale-javascript- development-11815324 ebooknice.com
(Ebook) Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript by Josh Goldberg ISBN 9781098110338, 1098110331 https://ebooknice.com/product/learning-typescript-enhance-your-web-development- skills-using-type-safe-javascript-43798584 ebooknice.com (Ebook) Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript by Josh Goldberg ISBN 9781098110338, 9781098110307, 1098110331, 1098110307 https://ebooknice.com/product/learning-typescript-enhance-your-web-development- skills-using-type-safe-javascript-44538720 ebooknice.com (Ebook) Large Scale Apps with React and TypeScript by Damiano Fusco https://ebooknice.com/product/large-scale-apps-with-react-and- typescript-47843004 ebooknice.com (Ebook) Large Scale Apps with Svelte and TypeScript by Damiano Fusco https://ebooknice.com/product/large-scale-apps-with-svelte-and- typescript-47843144 ebooknice.com (Ebook) Large Scale Apps with Vue, Vite and TypeScript by Damiano Fusco https://ebooknice.com/product/large-scale-apps-with-vue-vite-and- typescript-47843306 ebooknice.com
1. Preface a. How This Book Is Organized b. Style i. Conventions Used in This Book c. Using Code Examples d. O’Reilly Online Learning e. How to Contact Us f. Acknowledgments 2. 1. Introduction 3. 2. TypeScript: A 10_000 Foot View a. The Compiler b. The Type System i. TypeScript Versus JavaScript c. Code Editor Setup i. tsconfig.json ii. tslint.json d. index.ts e. Exercises 4. 3. All About Types a. Talking About Types b. The ABCs of Types
i. any ii. unknown iii. boolean iv. number v. bigint vi. string vii. symbol viii. Objects ix. Intermission: Type Aliases, Unions, and Intersections x. Arrays xi. Tuples xii. null, undefined, void, and never xiii. Enums c. Summary d. Exercises 5. 4. Functions a. Declaring and Invoking Functions i. Optional and Default Parameters ii. Rest Parameters iii. call, apply, and bind iv. Typing this v. Generator Functions
vi. Iterators vii. Call Signatures viii. Contextual Typing ix. Overloaded Function Types b. Polymorphism i. When Are Generics Bound? ii. Where Can You Declare Generics? iii. Generic Type Inference iv. Generic Type Aliases v. Bounded Polymorphism vi. Generic Type Defaults c. Type-Driven Development d. Summary e. Exercises 6. 5. Classes and Interfaces a. Classes and Inheritance b. super c. Using this as a Return Type d. Interfaces i. Declaration Merging ii. Implementations iii. Implementing Interfaces Versus Extending Abstract Classes
e. Classes Are Structurally Typed f. Classes Declare Both Values and Types g. Polymorphism h. Mixins i. Decorators j. Simulating final Classes k. Design Patterns i. Factory Pattern ii. Builder Pattern l. Summary m. Exercises 7. 6. Advanced Types a. Relationships Between Types i. Subtypes and Supertypes ii. Variance iii. Assignability iv. Type Widening v. Refinement b. Totality c. Advanced Object Types i. Type Operators for Object Types ii. The Record Type
iii. Mapped Types iv. Companion Object Pattern d. Advanced Function Types i. Improving Type Inference for Tuples ii. User-Defined Type Guards e. Conditional Types i. Distributive Conditionals ii. The infer Keyword iii. Built-in Conditional Types f. Escape Hatches i. Type Assertions ii. Nonnull Assertions iii. Definite Assignment Assertions g. Simulating Nominal Types h. Safely Extending the Prototype i. Summary j. Exercises 8. 7. Handling Errors a. Returning null b. Throwing Exceptions c. Returning Exceptions d. The Option Type
e. Summary f. Exercises 9. 8. Asynchronous Programming, Concurrency, and Parallelism a. JavaScript’s Event Loop b. Working with Callbacks c. Regaining Sanity with Promises d. async and await e. Async Streams i. Event Emitters f. Typesafe Multithreading i. In the Browser: With Web Workers ii. In NodeJS: With Child Processes g. Summary h. Exercises 10. 9. Frontend and Backend Frameworks a. Frontend Frameworks i. React ii. Angular 6/7 b. Typesafe APIs c. Backend Frameworks d. Summary
11. 10. Namespaces.Modules a. A Brief History of JavaScript Modules b. import, export i. Dynamic Imports ii. Using CommonJS and AMD Code iii. Module Mode Versus Script Mode c. Namespaces i. Collisions ii. Compiled Output d. Declaration Merging e. Summary f. Exercise 12. 11. Interoperating with JavaScript a. Type Declarations i. Ambient Variable Declarations ii. Ambient Type Declarations iii. Ambient Module Declarations b. Gradually Migrating from JavaScript to TypeScript i. Step 1: Add TSC ii. Step 2a: Enable Typechecking for JavaScript (Optional)
iii. Step 2b: Add JSDoc Annotations (Optional) iv. Step 3: Rename Your Files to .ts v. Step 4: Make It strict c. Type Lookup for JavaScript d. Using Third-Party JavaScript i. JavaScript That Comes with Type Declarations ii. JavaScript That Has Type Declarations on DefinitelyTyped iii. JavaScript That Doesn’t Have Type Declarations on DefinitelyTyped e. Summary 13. 12. Building and Running TypeScript a. Building Your TypeScript Project i. Project Layout ii. Artifacts iii. Dialing In Your Compile Target iv. Enabling Source Maps v. Project References vi. Error Monitoring b. Running TypeScript on the Server c. Running TypeScript in the Browser d. Publishing Your TypeScript Code to NPM
e. Triple-Slash Directives i. The types Directive ii. The amd-module Directive f. Summary 14. 13. Conclusion 15. A. Type Operators 16. B. Type Utilities 17. C. Scoped Declarations a. Does It Generate a Type? b. Does It Merge? 18. D. Recipes for Writing Declaration Files for Third- Party JavaScript Modules a. Types of Exports i. Globals ii. ES2015 Exports iii. CommonJS Exports iv. UMD Exports b. Extending a Module i. Globals ii. Modules 19. E. Triple-Slash Directives a. Internal Directives
b. Deprecated Directives 20. F. TSC Compiler Flags for Safety 21. G. TSX 22. Index
Programming TypeScript Making Your JavaScript Applications Scale Boris Cherny
Programming TypeScript by Boris Cherny Copyright © 2019 Boris Cherny. 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 corporate@oreilly.com.
Development Editor: Angela Rufino Indexer: Margaret Troutman Acquisitions Editor: Jennifer Pollock Interior Designer: David Futato Production Editor: Katherine Tozer Cover Designer: Karen Montgomery Copyeditor: Rachel Head Illustrator: Rebecca Demarest Proofreader: Charles Roumeliotis May 2019: First Edition Revision History for the First Edition 2019-04-18: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492037651 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming 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-492-03765-1 [LSI]
Dedication To Sasha and Michael, who might also fall in love with types, someday.
Preface This is a book for programmers of all walks: professional JavaScript engineers, C# people, Java sympathizers, Python lovers, Ruby aficionados, Haskell nerds. Whatever language(s) you write in, so long as you have some experience programming and know the basics of functions, variables, classes, and errors, this book is for you. Some experience with JavaScript, including a basic knowledge of the Document Object Model (DOM) and the network, will help you along the way—while we don’t dive deep into these concepts, they are a wellspring of excellent examples, and if you’re not familiar with them the examples might not make as much sense. Regardless of what programming languages you’ve used in the past, what unites all of us is our shared experience of tracking down exceptions, tracing through code line by line to figure out what went wrong and how we can fix it. This is the experience that TypeScript helps prevent by examining your code automatically and pointing out the mistakes you may have missed. It’s OK if you haven’t worked with a statically typed language before. I’ll teach you about types and how to use them effectively to make your programs crash less, document your
code better, and scale your applications across more users, engineers, and servers. I’ll try to avoid big words when I can, and explain ideas in a way that’s intuitive, memorable, and practical, using lots of examples along the way to help keep things concrete. That’s the thing about TypeScript: unlike a lot of other typed languages, TypeScript is intensely practical. It invents completely new concepts so you can speak more concisely and precisely, letting you write applications in a way that’s fun, modern, and safe.
How This Book Is Organized This book has two aims: to give you a deep understanding of how the TypeScript language works (theory) and provide bucketfuls of pragmatic advice about how to write production TypeScript code (practice). Because TypeScript is such a practical language, theory quickly turns to practice, and most of this book ends up being a mix of the two, with the first couple of chapters almost entirely theory, and the last few almost completely practice. I’ll start with the basics of what compilers, typecheckers, and types are. I’ll then give a broad overview of the different types and type operators in TypeScript, what they’re for, and how you use them. Using what we’ve learned, I’ll cover some advanced topics like TypeScript’s most sophisticated type system features, error handling, and asynchronous programming. Finally, I’ll wrap up with how to use TypeScript with your favorite frameworks (frontend and backend), migrating your existing JavaScript project to TypeScript, and running your TypeScript application in production. Most chapters come with a set of exercises at the end. Try to do these yourself—they’ll give you a deeper intuition for what we cover than just reading would. Answers for chapter exercises are available online, at https://github.com/bcherny/programming-typescript-answers.
Style Throughout this book, I tried to stick to a single code style. Some aspects of this style are deeply personal—for example: I only use semicolons when necessary. I indent with two spaces. I use short variable names like a, f, or _ where the program is a quick snippet, or where the structure of the program is more important than the details. Some aspects of the code style, however, are things that I think you should do too. A few of these are: You should use the latest JavaScript syntax and features (the latest JavaScript version is usually just called “esnext”). This will keep your code in line with the latest standards, improving interoperability and Googleability, and it can help reduce ramp-up time for new hires. It also lets you take advantage of powerful, modern JavaScript features like arrow functions, promises, and generators. You should keep your data structures immutable with spreads (...) most of the time. You should make sure everything has a type, inferred when possible. Be careful not to abuse explicit types; 1
this will help keep your code clear and terse, and improve safety by surfacing incorrect types rather than bandaiding over them. You should keep your code reusable and generic. Polymorphism (see “Polymorphism”) is your best friend. Of course, these ideas are hardly new. But TypeScript works especially well when you stick to them. TypeScript’s built-in downlevel compiler, support for read-only types, powerful type inference, deep support for polymorphism, and completely structural type system encourage good coding style, while the language remains incredibly expressive and true to the underlying JavaScript. A couple more notes before we begin. JavaScript doesn’t expose pointers and references; instead it has value and reference types. Values are immutable, and include things like strings, numbers, and booleans, while references point to often-mutable data structures like arrays, objects, and functions. When I use the word “value” in this book, I usually mean it loosely to refer to either a JavaScript value or a reference. Lastly, you might find yourself writing less-than-ideal TypeScript code in the wild when interoperating with JavaScript, or incorrectly typed third-party libraries, or legacy code, or if you’re in a rush. This book largely presents how you
should write TypeScript, and makes an argument for why you should try really hard not to make compromises. But in practice, how correct your code is is up to you and your team. 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, environment variables, statements, and keywords. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. 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://github.com/bcherny/programming-typescript-answers. 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 a CD-ROM of 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 do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming TypeScript by Boris Cherny (O’Reilly). Copyright 2019 Boris Cherny, 978-1-492-03765-1.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For almost 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, conferences, 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, please 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/programming-typescript. To comment or ask technical questions about this book, send email to bookquestions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments This book is the product of years’ worth of snippets and doodles, followed by a year’s worth of early mornings and nights and weekends and holidays spent writing. Thank you to O’Rielly for the opportunity to work on this book, and to my editor Angela Rufino for the support throughout the process. Thank you to Nick Nance for his contribution in “Typesafe APIs”, and to Shyam Seshadri for his contribution in “Angular 6/7”. Thanks to my technical editors: Daniel Rosenwasser of the TypeScript team, who spent an unreasonable amount of time reading through this manuscript and guiding me through the nuances of TypeScript’s type system, and Jonathan Creamer, Yakov Fain, and Paul Buying, and Rachel Head for technical edits and feedback. Thanks to my family—Liza and Ilya, Vadim, Roza and Alik, Faina and Yosif —for encouraging me to pursue this project. Most of all, thanks to my partner Sara Gilford, who supported me throughout the writing process, even when it meant calling off weekend plans, late nights writing and coding, and far too many unprompted conversations about the ins and outs of type systems. I couldn’t have done it without you, and I’m forever grateful for your support. 1 If you’re not coming from JavaScript, here’s an example: if you have an object o, and you want to add a property k to it with the value 3, you can either mutate o directly—o.k = 3—or you can apply your
change to o, creating a new object as a result—let p = {...o, k: 3}.
Chapter 1. Introduction So, you decided to buy a book about TypeScript. Why? Maybe it’s because you’re sick of those weird cannot read property blah of undefined JavaScript errors. Or maybe you heard TypeScript can help your code scale better, and wanted to see what all the fuss is about. Or you’re a C# person, and have been thinking of trying out this whole JavaScript thing. Or you’re a functional programmer, and decided it was time to take your chops to the next level. Or your boss was so fed up with your code causing production issues that they gave you this book as a Christmas present (stop me if I’m getting warm). Whatever your reasons are, what you’ve heard is true. TypeScript is the language that will power the next generation of web apps, mobile apps, NodeJS projects, and Internet of Things (IoT) devices. It will make your programs safer by checking for common mistakes, serve as documentation for yourself and future engineers, make refactoring painless, and make, like, half of your unit tests unnecessary (“What unit tests?”). TypeScript will double your productivity as a programmer, and it will land you a date with that cute barista across the street.
But before you go rushing across the street, let’s unpack all of that a little bit, starting with this: what exactly do I mean when I say “safer”? What I am talking about, of course, is type safety. TYPE SAFETY Using types to prevent programs from doing invalid things. Here are a few examples of things that are invalid: Multiplying a number and a list Calling a function with a list of strings when it actually needs a list of objects Calling a method on an object when that method doesn’t actually exist on that object Importing a module that was recently moved There are some programming languages that try to make the most of mistakes like these. They try to figure out what you really meant when you did something invalid, because hey, you do what you can, right? Take JavaScript, for example: 3 + [] // Evaluates to the string "3" let obj = {} obj.foo // Evaluates to undefined 1
function a(b) { return b/2 } a("z") // Evaluates to NaN Notice that instead of throwing exceptions when you try to do things that are obviously invalid, JavaScript tries to make the best of it and avoids exceptions whenever it can. Is JavaScript being helpful? Certainly. Does it make it easier for you to catch bugs quickly? Probably not. Now imagine if JavaScript threw more exceptions instead of quietly making the best of what we gave it. We might get feedback like this instead: 3 + [] // Error: Did you really mean to ad let obj = {} obj.foo // Error: You forgot to define the function a(b) { return b/2 } a("z") // Error: The function "a" expects // but you gave it a string. Don’t get me wrong: trying to fix our mistakes for us is a neat feature for a programming language to have (if only it worked
for more than just programs!). But for JavaScript, this feature creates a disconnect between when you make a mistake in your code, and when you find out that you made a mistake in your code. Often, that means that the first time you hear about your mistake will be from someone else. So here’s a question: when exactly does JavaScript tell you that you made a mistake? Right: when you actually run your program. Your program might get run when you test it in a browser, or when a user visits your website, or when you run a unit test. If you’re disciplined and write plenty of unit tests and end-to-end tests, smoke test your code before pushing it, and test it internally for a while before shipping it to users, you will hopefully find out about your error before your users do. But what if you don’t? That’s where TypeScript comes in. Even cooler than the fact that TypeScript gives you helpful error messages is when it gives them to you: TypeScript gives you error messages in your text editor, as you type. That means you don’t have to rely on unit tests or smoke tests or coworkers to catch these sorts of issues: TypeScript will catch them for you and warn you about them as you write your program. Let’s see what TypeScript says about our previous example: 3 + [] // Error TS2365: Operator '+' canno // and 'never[]'.
let obj = {} obj.foo // Error TS2339: Property 'foo' doe function a(b: number) { return b / 2 } a("z") // Error TS2345: Argument of type ' // parameter of type 'number'. In addition to eliminating entire classes of type-related bugs, this will actually change the way you write code. You will find yourself sketching out a program at the type level before you fill it in at the value level; you will think about edge cases as you design your program, not as an afterthought; and you will design programs that are simpler, faster, easier to understand, and easier to maintain. Are you ready to begin the journey? Let’s go! 1 Depending on which statically typed language you use, “invalid” can mean a range of things, from programs that will crash when you run them to things that won’t crash but are clearly nonsensical. 2 If you’re not sure what “type level” means here, don’t worry. We’ll go over it in depth in later chapters. 2
Chapter 2. TypeScript: A 10_000 Foot View Over the next few chapters, I’ll introduce the TypeScript language, give you an overview of how the TypeScript Compiler (TSC) works, and take you on a tour of TypeScript’s features and the patterns you can develop with them. We’ll start with the compiler. The Compiler Depending on what programming languages you worked with in the past (that is, before you decided to buy this book and commit to a life of type safety), you’ll have a different understanding of how programs work. The way TypeScript works is unusual compared to other mainstream languages like JavaScript or Java, so it’s important that we’re on the same page before we go any further. Let’s start broad: programs are files that contain a bunch of text written by you, the programmer. That text is parsed by a special program called a compiler, which transforms it into an abstract syntax tree (AST), a data structure that ignores things like whitespace, comments, and where you stand on the tabs versus spaces debate. The compiler then converts that AST to
a lower-level representation called bytecode. You can feed that bytecode into another program called a runtime to evaluate it and get a result. So when you run a program, what you’re really doing is telling the runtime to evaluate the bytecode generated by the compiler from the AST parsed from your source code. The details vary, but for most languages this is an accurate high-level view. Once again, the steps are: 1. Program is parsed into an AST. 2. AST is compiled to bytecode. 3. Bytecode is evaluated by the runtime. Where TypeScript is special is that instead of compiling straight to bytecode, TypeScript compiles to… JavaScript code! You then run that JavaScript code like you normally would—in your browser, or with NodeJS, or by hand with a paper and pen (for anyone reading this after the machine uprising has begun). At this point you may be thinking: “Wait! In the last chapter you said TypeScript makes my code safer! When does that happen?” Great question. I actually skipped over a crucial step: after the TypeScript Compiler generates an AST for your program—but before it emits code—it typechecks your code.
TYPECHECKER A special program that verifies that your code is typesafe. This typechecking is the magic behind TypeScript. It’s how TypeScript makes sure that your program works as you expect, that there aren’t obvious mistakes, and that the cute barista across the street really will call you back when they said they would. (Don’t worry, they’re probably just busy.) So if we include typechecking and JavaScript emission, the process of compiling TypeScript now looks roughly like Figure 2-1: Figure 2-1. Compiling and running TypeScript
Steps 1–3 are done by TSC, and steps 4–6 are done by the JavaScript runtime that lives in your browser, NodeJS, or whatever JavaScript engine you’re using. NOTE JavaScript compilers and runtimes tend to be smushed into a single program called an engine; as a programmer, this is what you’ll normally interact with. It’s how V8 (the engine powering NodeJS, Chrome, and Opera), SpiderMonkey (Firefox), JSCore (Safari), and Chakra (Edge) work, and it’s what gives JavaScript the appearance of being an interpreted language. In this process, steps 1–2 use your program’s types; step 3 does not. That’s worth reiterating: when TSC compiles your code from TypeScript to JavaScript, it won’t look at your types. That means your program’s types will never affect your program’s generated output, and are only used for typechecking. This feature makes it foolproof to play around with, update, and improve your program’s types, without risking breaking your application. The Type System Modern languages have all sorts of different type systems.
TYPE SYSTEM A set of rules that a typechecker uses to assign types to your program. There are generally two kinds of type systems: type systems in which you have to tell the compiler what type everything is with explicit syntax, and type systems that infer the types of things for you automatically. Both approaches have trade-offs. TypeScript is inspired by both kinds of type systems: you can explicitly annotate your types, or you can let TypeScript infer most of them for you. To explicitly signal to TypeScript what your types are, use annotations. Annotations take the form value: type and tell the typechecker, “Hey! You see this value here? Its type is type.” Let’s look at a few examples (the comments following each line are the actual types inferred by TypeScript): let a: number = 1 // a is a number let b: string = 'hello' // b is a string let c: boolean[] = [true, false] // c is an array of And if you want TypeScript to infer your types for you, just leave them off and let TypeScript get to work: let a = 1 // a is a number let b = 'hello' // b is a string 1
let c = [true, false] // c is an array of Right away, you’ll notice how good TypeScript is at inferring types for you. If you leave off the annotations, the types are the same! Throughout this book, we will use annotations only when necessary, and let TypeScript work its inference magic for us whenever possible. NOTE In general, it is good style to let TypeScript infer as many types as it can for you, keeping explicitly typed code to a minimum. TypeScript Versus JavaScript Let’s take a deeper look at TypeScript’s type system, and how it compares to JavaScript’s type system. Table 2-1 presents an overview. A good understanding of the differences is key to building a mental model of how TypeScript works.
Table 2-1. Comparing JavaScript’s and TypeScript’s type systems Type system feature JavaScript TypeScript How are types bound? Dynamically Statically Are types automatically converted? Yes No (mostly) When are types checked? At runtime At compile time When are errors surfaced? At runtime (mostly) At compile time (mostly) HOW ARE TYPES BOUND? Dynamic type binding means that JavaScript needs to actually run your program to know the types of things in it. JavaScript doesn’t know your types before running your program. TypeScript is a gradually typed language. That means that TypeScript works best when it knows the types of everything in your program at compile time, but it doesn’t have to know every type in order to compile your program. Even in an untyped program TypeScript can infer some types for you and catch some mistakes, but without knowing the types for
everything, it will let a lot of mistakes slip through to your users. This gradual typing is really useful for migrating legacy codebases from untyped JavaScript to typed TypeScript (more on that in “Gradually Migrating from JavaScript to TypeScript”), but unless you’re in the middle of migrating your codebase, you should aim for 100% type coverage. That is the approach this book takes, except where explicitly noted. ARE TYPES AUTOMATICALLY CONVERTED? JavaScript is weakly typed, meaning if you do something invalid like add a number and an array (like we did in Chapter 1), it will apply a bunch of rules to figure out what you really meant so it can do the best it can with what you gave it. Let’s walk through the specific example of how JavaScript evaluates 3 + [1]: 1. JavaScript notices that 3 is a number and [1] is an array. 2. Because we’re using +, it assumes we want to concatenate the two. 3. It implicitly converts 3 to a string, yielding "3". 4. It implicitly converts [1] to a string, yielding "1". 5. It concatenates the results, yielding "31".
We could do this more explicitly too (so JavaScript avoids doing steps 1, 3, and 4): 3 + [1]; // evaluates to "31" (3).toString() + [1].toString() // evaluates to "31" While JavaScript tries to be helpful by doing clever type conversions for you, TypeScript complains as soon as you do something invalid. When you run that same JavaScript code through TSC, you’ll get an error: 3 + [1]; // Error TS2365: Ope // types '3' and 'nu (3).toString() + [1].toString() // evaluates to "31" If you do something that doesn’t seem right, TypeScript complains, and if you’re explicit about your intentions, TypeScript gets out of your way. This behavior makes sense: who in their right mind would try to add a number and an array, expecting the result to be a string (of course, besides Bavmorda the JavaScript witch who spends her time coding by candlelight in your startup’s basement)? The kind of implicit conversion that JavaScript does can be a really hard-to-track-down source of errors, and is the bane of
many JavaScript programmers. It makes it hard for individual engineers to get their jobs done, and it makes it even harder to scale code across a large team, since every engineer needs to understand the implicit assumptions your code makes. In short, if you must convert types, do it explicitly. WHEN ARE TYPES CHECKED? In most places JavaScript doesn’t care what types you give it, and it instead tries to do its best to convert what you gave it to what it expects. TypeScript, on the other hand, typechecks your code at compile time (remember step 2 in the list at the beginning of this chapter?), so you don’t need to actually run your code to see the Error from the previous example. TypeScript statically analyzes your code for errors like these, and shows them to you before you run it. If your code doesn’t compile, that’s a really good sign that you made a mistake and you should fix it before you try to run the code. Figure 2-2 shows what happens when I type the last code example into VSCode (my code editor of choice).
Figure 2-2. TypeError reported by VSCode With a good TypeScript extension for your preferred code editor, the error will show up as a red squiggly line under your code as you type it. This dramatically speeds up the feedback loop between writing code, realizing that you made a mistake, and updating the code to fix that mistake. WHEN ARE ERRORS SURFACED? When JavaScript throws exceptions or performs implicit type conversions, it does so at runtime. This means you have to actually run your program to get a useful signal back that you did something invalid. In the best case, that means as part of a unit test; in the worst case, it means an angry email from a user. TypeScript throws both syntax-related errors and type-related errors at compile time. In practice, that means those kinds of errors will show up in your code editor, right as you type—it’s 2
an amazing experience if you’ve never worked with an incrementally compiled statically typed language before. That said, there are lots of errors that TypeScript can’t catch for you at compile time—things like stack overflows, broken network connections, and malformed user inputs—that will still result in runtime exceptions. What TypeScript does is make compile-time errors out of most errors that would have otherwise been runtime errors in a pure JavaScript world. Code Editor Setup Now that you have some intuition for how the TypeScript Compiler and type system work, let’s get your code editor set up so we can start diving into some real code. Start by downloading a code editor to write your code in. I like VSCode because it provides a particularly nice TypeScript editing experience, but you can also use Sublime Text, Atom, Vim, WebStorm, or whatever editor you like. Engineers tend to be really picky about IDEs, so I’ll leave it to you to decide. If you do want to use VSCode, follow the instructions on the website to get it set up. TSC is itself a command-line application written in TypeScript, which means you need NodeJS to run it. Follow the instructions on the official NodeJS website to get NodeJS up and running on your machine. 3 4
NodeJS comes with NPM, a package manager that you will use to manage your project’s dependencies and orchestrate your build. We’ll start by using it to install TSC and TSLint (a linter for TypeScript). Start by opening your terminal and creating a new folder, then initializing a new NPM project in it: # Create a new folder mkdir chapter-2 cd chapter-2 # Initialize a new NPM project (follow the prompts) npm init # Install TSC, TSLint, and type declarations for Node npm install --save-dev typescript tslint @types/node tsconfig.json Every TypeScript project should include a file called tsconfig.json in its root directory. This tsconfig.json is where TypeScript projects define things like which files should be compiled, which directory to compile them to, and which version of JavaScript to emit. Create a new file called tsconfig.json in your root folder (touch tsconfig.json), then pop it open in your code editor and give it the following contents: 5
Random documents with unrelated content Scribd suggests to you:
Quickly turning his horse’s head, the sturdy borderer ordered his troop to proceed eastward. “Don’t act too rashly, Captain,” entreated Penn. “General Braddock is ignorant of this country and Indian methods of warfare. He may have orders not to enlist native troops, yet without your aid I fear for the success of his expedition. Please let me intercede with him; he will do it when he hears that I am your friend.” “To the devil with him and his kind, the swinish snob,” growled Captain Jack, while his black eyes flashed a diabolical hatred; his Spanish temper was uncontrollable. That night, when Captain Jack and John Penn were seated at their camp fire at Laurel Run, a messenger, a Major, not a Sergeant Major, from General Braddock was announced. Saluting, the officer asked to be allowed to speak with John Penn, Esquire. Penn received the officer without rising, and was cooly civil throughout the interview, which consisted principally of reading a letter from Braddock, expressing deep regret “that he had not known that the son of his dear friend, Richard Penn, had been with –-- Jack,” and offering Penn the captaincy of Black Jack’s company of scouts, “–-- Jack to be First Lieutenant.” Naturally, Captain Jack was more enraged than ever, but he said: “Take it, John, I’ll withdraw and turn my men, who, you know, are the best shots in the Province, over to you. They would go through hell for you.” “Never fear,” replied Penn, and, turning to the Major, he said: “Tell General Braddock, with my compliments, that I decline to accept a commission which he has no authority to tender. As for my companion, Captain Jack (laying emphasis on the Captain) the General had his decision earlier in the day. Goodnight, Major.” Thus terminated the “conference” which might have changed the face of history. As the result of Braddock’s pride and folly, his defeat and death are a part of history, known by every Pennsylvanian. John Penn was wretchedly unhappy, even though Captain Jack tried to console him, when he shrewdly inferred that “Mary” had been kidnapped by emissaries of his relatives, and had not eloped with a vile serving man. His heart was too lacerated to remain longer
with the Wild Hunter, now that no active service was to be experienced; so, accompanied by Monkton, the veteran of Preston, he set out the next morning for the West Branch of the Susquehanna to the unexplored countries. At Waterford Narrows they passed the body of a trader recently killed and scalped by Indians. “May I draw one of his teeth, sir?” said the old soldier, “and you can carry it in your pocket, for the old people say ‘The only thing that can break the enchantment of love is the tooth of a dead man’.” Penn shook his head and rode on. For a considerable time Penn and Old Monkton visited with Dagonando (Rock Pine), a noted Indian Chief in Brush Valley (Centre County), for the young man, like the founder of Pennsylvania, possessed the same irresistible charm over the redmen. Years afterwards, in Philadelphia, speaking to General Thomas Mifflin, Dagonando stated that had it not been for his unhappy love affairs, John Penn would have been the equal of his grandfather as Governor, and prevented the Revolutionary War. But his spirit was crushed; even a mild love affair with Dagonando’s daughter ended with shocking disaster. Reaching Fort Augusta, Penn became very ill; a “nervous breakdown” his ailment would be diagnosed today. During his illness he was robbed of his diary. He reached Philadelphia in the fall, and almost immediately set sail for England. He remained abroad until 1763, when he returned as Governor of Pennsylvania. He arrived in Philadelphia on October 30, in the midst of the terrific earthquake of that year, and on November 5, George Roberts in a letter to Samuel Powell, in describing the new Chief Magistrate, says: “His Honor, Penn, is a little gentleman, though he may govern equal to one seven feet high.” Charles P. Keith has thus summed up Penn’s career from the time of his first arrival in Pennsylvania: “He was one of the Commissioners to the Congress at Albany in the summer of 1754, and made several journeys to the neighboring colonies. Nevertheless, his trouble made him again despondent; he began to shun company; he would have joined Braddock’s army had any
Pennsylvania troops formed part of it, and perhaps have died on the field which that officer’s imprudence made so disastrous. Some two months after the defeat he returned to England.” On June 6, 1766, a brilliant marriage occurred in Philadelphia. John Penn, Lieutenant Governor, aged thirty-seven years, married Anne, the daughter of William Allen, Chief Justice; a strange fate had united the relative of Peter Allen of “Tulliallan” to the husband of Maria Cox, pronounced legally dead after an absence of eleven years in parts unknown. Commenting on this alliance, Nevin Moyer, the gifted Historian, remarks: “The marriage was an unpleasant one, on his (Penn’s) account, for he was found very seldom at home.” It was during the wedding that a fierce electrical storm occurred, unroofing houses and shattering many old trees. It was not long after this marriage when a feeling of restlessness impelled him to start another of his many trips to the interior. This time it was given out that he wished to visit Penn’s Valley, the “empire” discovered in the central part of the province by Captains Potter and Thompson, and named in his honor, and Penn’s Cave, the source of the Karoondinha, a beautiful, navigable stream, rechristened “John Penn’s Creek.” He managed to stop over night, as everyone of any consequence did, at “Tulliallan,” and slept in the room with the Scotch thistles carved on the woodwork, and saw Peter Allen for the first time in twelve years. A foul crime had recently been committed in the neighborhood. Indian Joshua, who used to live at the running spring, had gone to Canada the year of Braddock’s defeat (the year of Mary’s disappearance, Penn always reckoned it) and had lately returned to his old abode. He had been shot, as a trail of blood from his cabin down the mountain had been followed clear to Clark’s Creek, where it was lost. In fact, pitiful wailing had been heard one night all the way across the valley, but it was supposed to be a traveling panther. Arvas, or Silver Heels, had also come back for a time, but, after Joshua’s disappearance, had gone away. “Maybe he killed his friend,” whispered Allen, looking down guiltily, as he spoke what he knew to be untruthful words.
“It is all clear to me now, Allen,” said Penn. “I should have believed Captain Jack, when in ’55 he told me that my late wife was carried off to Canada by Indians; the kidnappers came back, and for fear that they would levy hush money on those who had caused my Mary to be stolen, murdered Joshua as a warning.” Allen did not answer, but Penn said: “You have kept a public house so long that you have forgotten to be a gentleman, and I do not expect you to tell the truth.” In 1840 seekers after nestlings of the vultures climbed to the top of the King’s Stool, the dizzy pinnacle of the Third Mountain. There they found the skeleton of an Indian. It was all that was left of Joshua, who had climbed there in his agony and died far above the scenes which he loved so dearly. The hunters put the bones in their hunting pouches and climbed down the “needle,” and buried them decently at the foot of the rocks. The King’s Stool is named for a similar high point near Lough Foyle, Ireland, and there are also King’s Stools in Juniata and Perry Counties. The North of Ireland pioneers were glad to recognize scenes similar to the natural wonders of the Green Isle! A great light had come to John Penn, but he accepted his fate philosophically, just as he had the abuse heaped upon him for his vacillating policy towards the Indians. He followed up his vigorous attempt to punish the Paxtang perpetrators of the massacres of the Conestoga Indians at Christmas time, 1763, by promulgating the infamous scalp bounty of July, 1764, which bounty, to again quote Professor Moyer, paid “$134 for an Indian’s scalp, and $150 for a live Indian, and $50 for an Indian female or child’s scalp.” There are not enough Indians to make hunting for bounties in Pennsylvania a paying occupation today, so instead there is a bounty on Wildcats and foxes, wiping out desirable wild life to satisfy the politicians’ filthy greed. John Penn returned to Philadelphia without visiting Penn’s Valley or Penn’s Cave or John Penn’s Creek. He had seen them previously in 1755 when they bore their original Indian names, and his heart was still sad. It was not long after returning that he again started on another expedition up the Susquehanna, traveling by canoe, just as
his grandfather, William Penn, had done in his supposedly fabulous trip to the sources of the West Branch at Cherry Tree, in 1700. A stop was made at Fisher’s stone house, Fisher’s Ferry. A group of pioneers had heard of his coming and gave the little Governor a rousing ovation. He felt nearest to being happy when among the frontier people, who understood him, and his trials had, like Byron, made him “the friend of mountains”; he was still simple at heart. In the kitchen, seated by the inglenook, he heard someone’s incessant coughing in an inner room. He asked the landlord, old Peter Fisher, who was suffering so acutely. “Why, sir,” replied Fisher, “it’s an Englishwoman dying.” In those days people’s nationalities in Pennsylvania were more sharply defined, and any English-speaking person was always called an “Englishwoman” or an “Englishman,” as the case might be. “Tell me about her,” said the Governor, with ill-concealed curiosity. “It’s a strange story, it might give Your Worship offense,” faltered the old innkeeper. “They tell it, sir, though it’s doubtless a lie, that Your Excellency cared for this Englishwoman, and your enemies had her kidnapped by two Indians and taken to Canada. The Indians were paid for keeping her there until a few years ago, when their remittances suddenly stopped and they came home; one, it is said, was murdered soon after. Arvas, his companion, was accused of the crime, but he stopped here for a night, a few weeks afterwards, and swore to me that he was guiltless. The Englishwoman finally got away and walked all the way back from a place called Muskoka, but she caught cold and consumption on the way, and is on her death- bed now. I knew her in all her youth and beauty at Peter Allen’s, where she was always the belle of the balls there; she had been brought up a Quaker, but my, how she could dance. You would not know her now.” “I want to see her,” said the Governor, rising to his feet. It was getting dark, so Fisher lit a rushlight, and led the way. He opened the heavy door without rapping. His wife and daughter sat on high-backed rush-bottomed chairs on either side of the big four- poster bed, which had come from the Rhine country. On the bed lay a woman of about forty years, frightfully emaciated by suffering,
whose exaggeratedly clear-cut features were accentuated in their marble look by the pallor of oncoming dissolution. Her wavy, dark hair, parted in the middle, made her face seem even whiter. “Mary, Mary,” said the little Governor, as he ran to her side, seizing the white hands which lay on the flowered coverlet. “John, my darling John,” gasped the dying woman. “Leave us alone together,” commanded the Governor. The women looked at one another as they retired. The thoughts which their glances carried indicated “well, after all the story’s true.” They had been alone for about ten minutes when Penn ran out of the door calling, “Come quick, someone, I fear she’s going.” The household speedily assembled, but in another ten minutes “Mary Warren,” alias Maria Cox-Penn had yielded up the ghost. She is buried on the brushy African-looking hillside which faces the “dreamy Susquehanna,” the Firestone Mountains and the sunset, near where travelers across Broad Mountain pass every day. John Penn returned to Philadelphia and took no more trips to the interior. He divided his time between his town house, 44 Pine Street, and his country seat “Lansdowne.” During the Revolution he was on parole. He died childless. February 9, 1795, and is said to be buried under the floor, near the chancel, in the historic Christ Church, Philadelphia, which bears the inscription that he was “One of the Late Proprietors of Pennsylvania.” Most probably his body was later taken to England. His wife, nee Allen, survived him until 1813. The other night in the grand hall of the Historical Society of Pennsylvania in the Quaker City, a notable reception was given in honor of the grand historian-governor, William C. Sproul, fresh from his marvelous restoration of the Colonial Court House at Chester. As he stood there, the embodiment of mental and physical grace and strength, the greatest Governor of a generation, receiving the long line of those who came to pay their respects and well wishes, Albert Cook Myers, famed historian of the Quakers, mentioned that the present Governor of the Commonwealth was standing just beneath the portrait of John Penn, one of the last of the Proprietaries. And what a contrast there was! Penn looked so effete and almost
feminine with his child-like blonde locks, his pink cheeks, weak, half- closed mouth, his slender form in a red coat, so different from the vigorous living Governor. Penn was also so inferior to the other notable portraits which hung about him–the sturdy Huguenot, General Henri Bouquet, the deliverer of Fort Duquesne in 1758 and 1763; the stalwart Scot, General Arthur St. Clair, of Miami fame, who was left to languish on a paltry pension of $180 a year at his rough, rocky farm on Laurel Ridge; the courageous-looking Irishman, General Edward Hand; and, above all, the bold and dashing eagle face of General “Mad Anthony” Wayne. Such company for the last of the Penns to keep! Though lacking the manly outlines of his fellows on canvas, who can say that his life had one whit less interest than theirs–probably much more so, for his spirit had felt the thrill of an undying love, which in the end surmounted all difficulties and left his heart master of the field. Though his record for statecraft can hardly be written from a favorable light, and few of his sayings or deeds will live, he has joined an immortal coterie led down the ages by Anthony and the beautiful Egyptian queen, by Abelard and Heloise, Dante and Beatrice, Petrarch and Laura, Alfieri and the Countess of Albany, and here in Pennsylvania by Hugh H. Brackenridge and the pioneer girl, Sabina Wolfe, and Elisha Kent Kane, and the spiritualist, Maria Fox. Love is a force that is all-compelling, all-absorbing and never dies, and is the biggest thing in life, and the story of John Penn and Maria Cox will be whispered about in the backwoods cabins and wayside inns of the Pennsylvania Mountains long after seemingly greater men and minds have passed to forgetfulness. But for a few lines in the writings of Charles P. Keith, H. M. Jenkins, Nevin W. Moyer and various Penn biographers, such as Albert Cook Myers, the verbal memories of ’Squire W. H. Garman, James Till, Mrs. H. E. Wilvert and other old-time residents of the vicinity of “Tulliallan,” all would be lost, and the inspiration of a story of overwhelming affection unrecorded in the annals of those who love true lovers.
II At His Bedside When old Jacob Loy passed away at the age of eighty years, he left a pot of gold to be divided equally among his eight children. It was a pot of such goodly proportions that there was a nice round sum for all, and the pity of it was after the long years of privation which had collected it, that some of the heirs wasted it quickly on organs, fast horses, cheap finery and stock speculations, for it was before the days of player-pianos, victrolas and automobiles. Yolande, his youngest daughter, was a really attractive girl, even had she not a share in the pot of gold, and had many suitors. Though farm raised and inured to hardships she was naturally refined, with wonderful dark eyes and hair, and pallid face–the perfect type of Pennsylvania Mountain loveliness. Above all her admirers she liked best of all Adam Drumheller, a shrewd young farmer of the neighborhood, and eventually married him. Three children were born in quick succession, in the small tenant house on his father’s farm in Chest Township, where the young couple had gone to live immediately after their wedding. Shortly after the birth of the last child old Jacob Drumheller died, and the son and his family moved into the big stone farmhouse near the banks of the sulphurous Clearfield Creek. It was not long after this fortuitous move that the young wife began to show signs of the favorite Pennsylvania mountain malady–consumption. Whether it was caused by a deep-seated cold or came about from sleeping in rooms with windows nailed shut, no one could tell, but the beautiful young woman became paler and more wax-like, until she realized that a speedy end was inevitable. Many times she found comfort in
her misfortune by having her husband promise that in the event of her death he would never remarry. “Never, never,” he promised. “I could never find your equal again.” He was sincere in some respects; it would be hard to find her counterpart, and she had made a will leaving him everything she possessed, and he imagined that the pot of gold transformed into a bank balance or Government bonds would be found somewhere among her effects. Before ill health had set in he had quizzed her many times, as openly as he dared, on the whereabouts of her share of the pot. “It is all safe,” she would say. “It will be forthcoming some time when you need it more than you do today,” and he was satisfied. As she grew paler and weaker Adam began to think more of Alvira Hamel, another comely girl whom he had loved when he railroaded out of Johnstown, at Kimmelton, and whom he planned to claim as his own should Yolande pass away.
SCENE IN SNYDER-MIDDLESWARTH PARK Perhaps his thoughts dimly reflected on the dying wife’s sub- conscious mind, for she became more insistent every day that he promise never to remarry. “Think of our dear little children,” she kept saying, “sentenced to have a stepmother; I would come back and haunt you if you perpetrate such a cruelty to me and mine.” Adam had little faith in a hereafter, and less in ghosts, so he readily promised anything, vowing eternal celebacy cheerfully and profoundly.
When Yolande did finally fade away, she died reasonably happy, and at least died bravely. She never shed a tear, for it is against the code of the Pennsylvania Mountain people to do so–perhaps a survival of the Indian blood possessed by so many of them. Three days after the funeral Adam hied himself to Ebensburg to “settle up the estate,” but also to look up Alvira Hamel, who was now living there. She seemed glad to see him, and when he broached a possible union she acted as if pleased at everything except to go on to that lonely farm on the polluted Clearfield Creek. By promising to sell out when he could and move to Barnesboro or Spangler, a light came in her dark eyes, and though he did not visit the lawyer in charge of his late wife’s affairs, his day in town was successful in arranging for the new alliance with his sweetheart of other days. In due course of time it was discovered that the equivalent of Yolande’s share of the pot of gold left by old Jacob Loy was not to be found. “She may have kept it in coin and buried it in the orchard,” was some of the very consoling advice that the lawyer gave. At any rate it was not located by the time that Adam and Alvira were married, but the bridegroom was well to do and could afford to wait. After a short trip to Pittsburg and Wheeling the newly married couple took up housekeeping in the big brick farmstead above the creek. The first night that they were back from the honeymoon–it was just about midnight and Alvira was sleeping peacefully–Adam thought that he heard footsteps on the stairs. He could not be mistaken. Noiselessly the door opened, and the form of Yolande glided into the room; she was in her shroud, all white, and her face was whiter than the shroud, and her long hair never looked blacker. Along the whitewashed wall by the bedside was a long row of hooks on which hung the dead woman’s wardrobe. It had never been disturbed; Alvira was going to cut the things up and make new garments out of them in the Spring. Adam watched the apparition while she moved over to the clothing, counting them, and smoothed and caressed each skirt or waist, as if she regretted having had to abandon them for the steady raiment of the shroud.
Then she came over to the bed and sat on it close to Adam, eyeing him intently and silently. Just then Alvira got awake, but apparently could see nothing of the ghost, although the room was bright as day, bathed in the full moon’s light. Yolande seemed to remain for a space of about ten minutes, then passed through the alcove into the room where the children were sleeping and stood by their bedside. The next night she was back again, repeating the same performance, the next night, and the next, and still the next, each night remaining longer, until at last she stayed until daybreak. In the morning as the hired men were coming up the boardwalk which led to the kitchen door, they would meet Yolande, in her shroud coming from the house, and passing out of the back gate. On one occasion Alvira was pumping water on the porch, but made no move as she passed, being evidently like so many persons, spiritually blind. The hired men had known Yolande all their lives, and were surprised to see her spooking in daylight, but refrained from saying anything to the new wife. Every day for a week after that she appeared on the kitchen porch, or on the boardwalk, in the yard, on the road, and was seen by her former husband many times, and also her night prowling went on as of yore. The hired men began to complain; it might make them sick if a ghost was around too much; these spooks were supposed to exhale a poison much as copperhead snakes do, and also draw their “life” away, and they threatened to quit if she wasn’t “laid.” All of them had seen spooks before, on occasion, but a daily visitation of the same ghost was more than they cared about. Had it not been for the excitable hired men, Adam, whose nerves were like iron, could have stood Yolande’s ghost indefinitely. In fact, he thought it rather nice of her to come back and see him and the children “for old time’s sake.” But the farm hands must be conserved at any cost, even to the extent of laying Yolande’s unquiet spirit. The next night when she appeared, he made bold and spoke to her: “What do you want, Yolande,” he said softly, so as not to wake the soundly sleeping Alvira at his side. “Is there anything I can do for you, dear?”
Yolande came very close beside him, and bending down whispered in his ear: “Adam,” said she, “how can you ask me why I am here? You surely know. Did you not, time and time again, promise never to marry again, if I died, for the sake of our darling children? Did you not make such a promise, and see how quickly you broke it! Where I am now I can hold no resentments, so I forgive you for all your transgressions, but I hope that Alvira will be good to our children. I have one request to make: After I left you, you were keen to find what I did with my share of daddy’s pot of gold. I had it buried in the orchard at my old home, under the Northern Spy, but after we moved here, one time when you went deer hunting to Centre County, I dug it up and brought it over here and buried it in the cellar of this house. It is here now. There are just one hundred and fifty-three twenty dollar gold pieces; that was my share. The children and the money were on my mind, not your broken promise and rash marriage, which you will repent, and which I tell you again I forgive you for. I want my children to have that money, every one of the one hundred and fifty-three twenty dollar gold pieces. I buried it a little to the east of the spring in the cellar, about two feet under ground, in a tin cartridge box; Dig it up tomorrow morning, and if you find the one hundred and fifty-three coins, and give every one to the children, I will never come again and upset your hired men. Why I have Myron Shook about half scared to death already, but if you don’t find every single coin I’ll have to come back until you do, or if you hold it back from the children, you will not be able to keep a hireling on this place, or any other place to which you move. Many live folks can’t see ghosts; your wife is one of these; she will never worry until the hired men quit, then she’ll up and have you make sale and move to town. Be square and give the children the money, and I’ll not trouble you again.” “Oh, Yolande,” answered Adam in gentle tones, “you are no trouble to me, not in the least. I love to have you visit me at night, and look at the children, but you are making the hired help terribly uneasy. That part you must quit.” “That’s enough of your drivel, Adam,” spoke Yolande, in a sterner tone of voice. “Talk less like a fool, and more like a man. Dig up that
money in the morning, count it, and give it to the children and I’ll be glad never to see you again.” To be reproached by a ghost was too much for Adam, and he lapsed into silence, while Yolande slipped out of the room, over to the bedside of the sleeping children, where she lingered until daylight. Adam was soon asleep, but was up bright and early the next morning, starting to dress just as the ghost glided out of the door. By six o’clock he had exhumed Yolande’s share of the pot of gold which was buried exactly as her ghostly self had described. It was a hard wrench to hand the money over to the children, or rather to take it to Ebensburg and start savings accounts in their names. But he did it without a murmur. The cashier, a horse fancier, gave him a present of a new whip, of a special kind that he had made to order at Pittsburg, so he came home happy and contented. Night was upon him, and supper over, he retired early, dozing a bit before the “witching hour.” As the old Berks County tall clock in the entry struck twelve, he began to watch for Yolande’s accustomed entrance. But not a shadow appeared. The clock struck the quarter, the half, three quarters and one o’clock. No Yolande or anything like her came; she was true to her promise, as true as he had been false. It was an advantage to be a ghost in some ways. They were honorable creatures. Adam did not know whether to feel pleased or not. His vanity had been not a little appealed to by a dead wife visiting him nightly; now he was sure that it wasn’t for love of him or jealousy, she had been coming back, but to see that the children got the money that had been buried in the cellar. And at last she had spoken rather unkindly, so the great change called death had ended her love, and she wasn’t grieving over his second marriage at all. However, he fell to consoling himself that she had chided him for breaking his word and marrying again; she must have cared for him or she would not have said those things. Then the thought came to him that she wasn’t really peeved at anything concerning his marriage to Alvira except that the children had gotten a stepmother. He wondered if Alvira would continue to be kind to them. Just as he went to sleep he had
forgotten both Yolande and Alvira, chuckling over a pretty High School girl he had seen on the street at the ’burg, and whom he had winked at.
III. The Prostrate Juniper Weguarran was a young warrior of the Wyandots, who lived on the shores of Lake Michigan. In the early spring of 1754 he was appointed to the body-guard of old Mozzetuk, a leader of the tribe, on an embassy to Bethlehem, in Pennsylvania, to prevail on the holy men there, as many Indians termed the Moravians, to send a band of Missionaries to the Wyandot Country, with a view of Christianizing the tribe, and acting as advisors and emissaries between the Wyandots and allied nations with the French and other white men, who were constantly encroaching on the redmen’s territories. Weguarran the youngest and the handsomest of the escort, was very impressionable, and across Ohio and over the Alleghenies, he made friends with the Indian maidens of the various encampments passed en route. The reception at Bethlehem was cordial, but not much hope was held out for an immediate despatch of Missionaries as the Moravians were anxious to avoid being drawn into the warlike aspirations of the English and French, preferring to promote the faith in pacified regions, as very few of them were partisans, but if they had a leaning at all, it was toward the French. This was due to the fact that the French always understood the Indians better than the English, were more sympathetic colonizers, and while many French Missionaries carried forward the tenets of Rome, there was no religious intolerance, and Missionaries of every faith seemed to thrive under their leadership. While at Bethlehem and Nazareth, Weguarran was much favored by the Indian maids of those localities, but did not wholly lose his
heart until one afternoon at the cabin of an old Christian Pequot named Michaelmas. This old Indian, a native of Connecticut, lived in a log cabin on a small clearing near the Lehigh River, where he cultivated a garden of rare plants and trees, and raised tobacco. All his pastimes were unusual; he captured wild pigeons, which he trained to carry messages, believing that they would be more valuable in wartime than runners. He also practiced falconry, owning several hawks of race, goshawks, marsh hawks and duck hawks. The goshawks he used for grouse, wood-cocks and quails; the marsh hawks for rabbits, hares and ’coons; and the duck hawks for wild ducks and other water birds, which fairly swarmed on the Lehigh in those days. He was a religious old man, almost a recluse, strong in his prejudices, and was much enthused by the Wyandot embassy, giving his waning hopes a new burst of life for an Indian renaissance. He took a great fancy to the manly and handsome Weguarran, inviting him to his cabin, and it was there that the youthful warrior met the old man’s lovely daughter, Wulaha. She was an only child, eighteen years of age. Her mother belonged to the Original People and was also a Christian. Love progressed very rapidly between Weguarran and Wulaha, and as the time drew near for the embassy to depart, the young girl intimated to her lover that he must discuss the subject with old Michaelmas, and secure his approval and consent, after the manner of white Christians. The old Pequot was not averse to the union, which would add another strain of Indian blood to the family, but stated that a marriage could only take place on certain conditions. Weguarran, in his conversations with Michaelmas, had told him of his military affiliations with the French, which had filled the old man’s heart with joy for the hopes of a new order of things that it seemed to kindle. When he asked the hand of the fair Wulaha in marriage, Michaelmas “came back” with the following proposition: “Weguarran, I am getting old and feeble,” he said. “I may pass away any time, and I could not bear the thought of my squaw being left alone, which would be the case if you married Wulaha and took
her to the distant shores of Lake Michigan. However, there are greater things than my death and my squaw’s loneliness, the future of the red race, now crushed to earth by the Wunnux, as we call the white men, but some day to be triumphant. You have told me that within this very year the French and Indians are sure to engage the English in a mighty battle which will decide the future history of the Continent. You can marry Wulaha right after that battle, if you are victorious; otherwise you can do as the Missionaries tell us the Romans did–fall on your sword. You can never return here, as I do not want my daughter to marry and continue the race of a beaten people. I would far rather have her die single, and have our seed perish, for if this victory is not won, doomed is every redman on this Continent. The only wish of the English is to encompass our extermination. Wulaha will remain at home until after that battle, when you can come for her and claim her as your own, and we will give her to you with rejoicing.” “What you say is surely fair enough, Father Michaelmas,” replied Weguarran, “for I would see no future for Wulaha and myself if the English are victorious in this inevitable battle. As soon as it is won– and it will be won, for the high resolve of every Indian warrior is to go in to win–I will hurry back to the banks of the Lehigh, never stopping to rest, sleep or eat, to tell you of the glad tidings, and bear away my beloved Wulaha. I want to ask one special favor of you. I have admired your wonderful cage of trained wild pigeons, which you say will carry messages hundreds of miles. Lend me one of these pigeons, and as soon as the victory is won, I will release the bird, and while I am speeding eastward on foot, our feathered friend will fly on ahead and end the suspense, and bring joy to yourself, your squaw and Wulaha.” “I will gladly let you have my best trained pigeon, or hawk, or anything I possess, if I can learn of the victory, but in turn I will ask a favor of you. I listened with breathless interest to your tales of the Prostrate Junipers which grow on the shores of the great lakes, which cover two thousand square feet, and are hundreds of years old. You promised to bring me a scion of one of those curious trees, so that I might plant it in my garden of rare trees and shrubs. Now,
here will be a chance to associate it with the great victory; pluck a stout but small scion, and if the victory is won, affix it firmly to one of the pigeon’s legs and let it go. If it comes back without the twig of Juniper I will know that our cause has lost, and while you fall on your sword, I and my family will jump into the Lehigh.” “I will gladly do as you say, Father Michaelmas,” said Weguarran, “and will send a twig that will grow, and some day make a noble tree, and in years to come, our people will call it Weguarran’s Victory Tree. The fact that it is a Prostrate Tree makes it all the more appropriate, as it will represent the English race lying prostrated, crushed by the red race they wronged, and by our kindly and just French allies.” Weguarran was so inspired by the thought of the pigeon messenger, the sprig of Prostrate Juniper, and the impending victory that it assuaged his grief at the parting from Wulaha, sending him away determined to give a good account of himself in all things. Old Michaelmas selected a handsome cock pigeon, with a dragon’s blood red breast–his very best and most intelligent, and surest flyer, named Wuskawhan, which he placed in a specially built, bottle shaped basket, which had no lid, yet the top was too small for the bird to escape. In this way it could rise up and peer out, as it was carried along, and not bruise its wing coverts or head, as it would if it flew against the top of a square basket with a lid. After a touching parting with Wulaha, her mother and father, the young warrior went his way with his precious burden. The Indians, even old Mozzetuk, were rapid travellers, and in due time they reached the country of the Prostrate Junipers on the shores of Lake Michigan. They arrived in what seemed like an armed camp, for all the braves had been called to arms, which plotted to drive Indians and French to the uttermost ends of the earth. Weguarran was quickly mobilized, and a musket in one hand and tomahawk in the other, while on his back he bore the sacred pigeon, he marched toward his foes. In the excitement he had not forgotten to slip into his pouch at his belt a sprig of the Prostrate Juniper, which would be the emblem of the English race prostrate under the foot of French and Indian allies.
In due course of time the army of which the picked Wyandot warriors formed a part, met their English foemen on Braddock’s Field, completely routing and all but annihilating them. General Braddock himself was shot from behind by one of his own men in the wild stampede, and the French and Indians were completely victorious. Surveying the gorey scene, every wooded glade lying thick with dead redcoats and broken accoutrements, Weguarran carefully opened the panther skin pouch at his best, taking out the sprig of Prostrate Juniper. Then he lifted the handsome wild pigeon from its bottle-nosed cage of oak withes, and with a light leathern string, affixed the little twig, on which the berries still clustered, to the bird’s leg, then tossed the feathered messenger up into the air. The pigeon quickly rose above the trees, circled a few times, and then started rapidly for the east, as fast as his broad, strong wings could carry him. This done, Weguarran visited his chief, obtaining leave to proceed to Bethlehem to claim his bride, promising to report back with her on the banks of the Ohio as speedily as possible. The pigeon naturally had a good start, and by the next morning was flying over the palisaded walls of John Harris’ Trading Post on the Susquehanna. A love story was being enacted within those walls, in the shadow of one of the huge sheds used in winter to store hides. Keturah Lindsay, Harris’ niece, an attractive, curly-haired Scotch girl, was talking with a young Missionary whom she admired very much, Reverend Charles Pyrleus, the protege of Col. Conrad Weiser. Unfortunately they had to meet by stealth as his attentions were not favored by the girl’s relatives, who considered him of inferior antecedents. They had met in the shed this fair July morning, whether by design or accident, no one can tell, and were enjoying one another’s society to the utmost. In the midst of their mutual adoration, the dinner gong was sounded at the trading house, and Keturah, fearful of a scolding, reluctantly broke away. As she came out into the sunlight, she noticed a handsome wild pigeon drop down, as if exhausted, on one
of the topmost stakes of the palisade which surrounded the trading house and sheds. Keturah, like many frontier girls, always carried a gun, and quickly taking aim, fired, making the feathers fly, knocking the bird off its perch, and it seemed to fall to the ground outside the stockade. In a minute it rose, and started to fly off towards the east. She had reloaded, so fired a second time, but missed. “How strange to see a wild pigeon travelling through here at this time of year,” she thought, as carrying her smoking firearm, she hurried to the mess room of the big log trading house. The messenger pigeon had been grievously hurt, but was determined to go “home.” On and on it went, sometimes “dipping” like a swallow, from loss of blood, but by sheer will power keeping on the wing. As it neared the foothills of the South Mountains, near the village of Hockersville, with old Derry Church down in the vale, it faltered, spun about like a pin wheel, and fell with a thud. Gulping and blinking a few times, it spread out its wide pinions and lay on its breastbone–stone dead–the twig of Prostrate Juniper still affixed to one of its carmine feet. There it lay, brave in death, until the storms and winds shivered it, and it rotted into the ground. Weguarran was a rapid traveler, and in forced marches came to the shady banks of the Lehigh in three or four days. He was so excited that he swam the stream. He brought the first news of the great victory in the west to the surprised Michaelmas and his friends. But where was the prized wild pigeon, Wuskawhan? It could not have gone astray, for such a bird’s instinct never erred. “Caught by a hawk or shot down by some greedy fool of a Wunnux” was the way in which old Michaelmas explained its non-appearance. The news spread to the white settlements and to the towns, and there was consternation among all sympathizers with the Crown– with all except a few Moravians who were mum for policy’s sake, and the Indians, whose stoical natures alone kept them from disclosing the elation that was in their hearts.
A MAMMOTH SHORT-LEAF PINE “The English never wanted the Indians civilized,” said Michaelmas, boldly. “They drove the Moravians out of Schadikoke and from the Housatonic when they saw the progress they made with our people; were it not for the Quakers in Pennsylvania, they would have had no place to harbor; those of us who felt the need of these kind friends followed them in their exile, but we can never forgive that we had to leave the Connecticut country of our birth under such circumstances. I am glad that our enemies were beaten and annihilated.” Weguarran was baptized, and he and the lovely Wulaha were married by one of the Moravian preachers, and started for the great lake country, which was to be their permanent home.
Michaelmas and his squaw were too old to make the long journey, but they were happy in their garden of rare trees and plants, the wild pigeons, the hawks of race, and the dreams of an Indian renaissance. They lived many years afterwards, and are buried with the other Christian Indians at Bethlehem. Out in the foothills of the South Mountains, overlooking old Derry Church, in the fertile Lebanon Valley among the pines and oaks and tulip trees, a strange seedling appeared in the spring of 1756, different from anything that the mountain had known since prehistoric times. Instead of growing upward and onward as most brave trees do, it spread out wider and greater and vaster, until, not like the symbol of the Anglo-Saxon prone beneath the heel of French and Indian, it was the symbol of the all diffusing power of the English speaking race, which has grafted its ideals and hopes and practical purposes over the entire American Continent. Nourished by the life’s blood of the travelling pigeon that bore it there, it had a flying start in the battle of existence, and today, after all these years, bids fair to last many years longer, to be the arboral marvel and wonder of the Keystone State. Well may the Boy Scouts of Elizabethtown feel proud to be the honorary custodians of this unique tree with its spread of 2,000 feet, for apart from its curious appearance and charm, it has within it memories of history and romance, of white men and red, that make it a veritable treasure trove for the historian and the folk-lorist, and all those who love the great outdoors in this wonderful Pennsylvania of ours!
IV. Out of the Ashes Last Autumn we were crossing Rea’s Hill one afternoon of alternate sunshine and shadow, and as we neared the summit, glanced through several openings in the trees at the wide expanse of Fulton County valleys and coves behind us, on to the interminable range upon range of dark mountains northward. In the valleys here and there were dotted square stone houses, built of reddish sandstone, with high roofs and chimneys, giving a foreign or Scottish air to the scene. Some of these isolated structures were deserted, with windows gaping and roofs gone, pictures of desolation and bygone days. Just as the crest of the mountain was gained, we came upon a stone house in process of demolition, in fact all had been torn away, and the sandstone blocks piled neatly by the highway, all but the huge stone chimney and a small part of one of the foundation walls. Work of the shorers had temporarily ceased for it was a Saturday afternoon. Affixed to the chimney was a wooden mantel, painted black, of plain, but antique design, exposed, and already stained by the elements, and evidently to be abandoned by those in charge of the demolition. The house stood on the top of a steep declivity, giving a marvelous view on four sides, almost strategic enough to have been a miniature fortress! It was the first time in a dozen years that we had passed the site; in 1907 the house was standing and tenanted, and pointed out as having been a temporary resting place of General John Forbes on his eastern march, after the successful conquest of Fort Duquesne, in
1758. Now all is changed, historic memories had not kept the old house inviolate; it was to be ruthlessly destroyed, perhaps, like the McClure Log College near Harrisburg, to furnish the foundations for a piggery, or some other ignoble purpose. As we passed, a pang of sorrow overcame us at the lowly state to which house and fireplace had fallen, and we fell to recounting some of the incidents of the historic highway, in military and civil history, the most noteworthy road in the Commonwealth. The further, on we traveled, the more we regretted not stopping and trying to salvage the old wooden mantel, but one of our good friends suggested that if we did not are to return for it, we should mention the matter to the excellent and efficient Leslie Seylar at McConnellsburg, who knew everyone and everything, and could doubtless obtain the historic relic and have it shipped to our amateur “curio shop.” The genial Seylar, famed for his temperamental and physical resemblance to the lamented “Great Heart,” was found at his eyrie and amusement centre on top of Cove Mountain, and he gladly consented to securing the abandoned mantel. As a result it is now in safe hands, a priceless memento of the golden age of Pennsylvania History. But now for the story or the legend of the mantel, alluded to briefly last year in the chapter called the “Star of the Glen,” in this writer’s “South Mountain Sketches.” The story, as an old occupant of the house told it, and he survived on until early in the Nineteenth Century was, that General Forbes, on this victorious eastern march, was seized many times with fainting fits. On every occasion his officers and orderlies believed that the end had come, so closely did he simulate death. But he had always been delicate, at least from his first appearance in Pennsylvania, though when campaigning with the gallant Marshal Ligonier in France, Flanders and on the Rhine, participating in the battles of Dettingen, Fontenoy and Lauffeld, no such symptoms were noted. Although less than fifty years of age when he started towards the west, he was regarded, from his illnesses, as an aged person, Sherman Day in his inimitable “Historical Collections” states that there was “much dissatisfaction in
the choice of a leader of the expedition against Fort Duquesne, as General Forbes, the commander, was a decrepit old man.” What caused his ill health history has not uncovered at this late date. It has been said that he was an epileptic, like Alexander and other great generals, or a sufferer from heart trouble or general debility. His military genius outweighed his physical frailties, so that he rose superior to him, but it must not be forgotten that he was aided by two brilliant officers, Colonel George Washington and Colonel Henry Bouquet. His immediate entourage was a remarkable one, even for a soldier of many wars. Like a true Scotsman, he carried his own piper with him, Donald MacKelvie, said to be a descendant of the mighty MacCrimmons; and his bodyguard was also headed by a Highlander, Andrew MacCochran, who had been a deer stalker on one of the estates owned by the General’s father. Forbes himself, being a younger son, was not a man of property, and Pittencrief House, his birth-place, was already occupied by an older brother, from whom, so Dr. Burd S. Patterson tells us, all who claim relationship to him are descended. The General was carried in a hammock, with frequent stops, from Harris’ Ferry to Fort Duquesne, and back again, borne by four stalwart Highlanders, in their picturesque native costumes, wearing the tartan of the Forbes clan. The deerstalker, MacCochran, was the major domo, and even above the chief of staff and Brigade Surgeon, gave the orders to halt when the General’s lean weazened face indicated an over-plussage of fatigue. It was late in the afternoon as the returning army had neared the summit of Rea’s Hill; the pipers were playing gaily Blaz Sron, to cheer foot soldiers and wagoners up the steep, rocky, uneven grade, with the General in the van. The ascent was a hard one, and the ailing commander-in-chief was shaken about considerably, so much so that MacCochran was glad to note the little stone house, where he might give him his much needed rest. Old Andrew McCreath and his wife, a North of Ireland couple, the former a noted hunter, occupied the house; their son was serving in the Pennsylvania Regiment, which formed a part of General Forbes’
Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebooknice.com

(Ebook) Programming TypeScript: Making Your JavaScript Applications Scale by Boris Cherny

  • 1.
    Instant Ebook Access,One Click Away – Begin at ebooknice.com (Ebook) Programming TypeScript: Making Your JavaScript Applications Scale by Boris Cherny https://ebooknice.com/product/programming-typescript-making- your-javascript-applications-scale-38567168 OR CLICK BUTTON DOWLOAD EBOOK Get Instant Ebook Downloads – Browse at https://ebooknice.com
  • 2.
    Instant digital products(PDF, ePub, MOBI) ready for you Download now and discover formats that fit your needs... Start reading on any device today! (Ebook) Programming TypeScript: Making your JavaScript applications scale by Boris Cherny ISBN 9781492037651, 9781492037620, 1492037656, 1492037621 https://ebooknice.com/product/programming-typescript-making-your-javascript- applications-scale-33607784 ebooknice.com (Ebook) Programming TypeScript by Boris Cherny ISBN 9781492037651, 1492037656 https://ebooknice.com/product/programming-typescript-10479588 ebooknice.com (Ebook) Pro TypeScript: Application-Scale JavaScript Development by Steve Fenton ISBN 9781484232484, 9781484232491, 1484232488, 1484232496 https://ebooknice.com/product/pro-typescript-application-scale-javascript- development-6840582 ebooknice.com (Ebook) Pro TypeScript: application-scale javascript development by Fenton, Steve ISBN 9780932633422, 9781484232484, 9781484232491, 0932633420, 1484232488, 1484232496 https://ebooknice.com/product/pro-typescript-application-scale-javascript- development-11815324 ebooknice.com
  • 3.
    (Ebook) Learning TypeScript:Enhance Your Web Development Skills Using Type-Safe JavaScript by Josh Goldberg ISBN 9781098110338, 1098110331 https://ebooknice.com/product/learning-typescript-enhance-your-web-development- skills-using-type-safe-javascript-43798584 ebooknice.com (Ebook) Learning TypeScript: Enhance Your Web Development Skills Using Type-Safe JavaScript by Josh Goldberg ISBN 9781098110338, 9781098110307, 1098110331, 1098110307 https://ebooknice.com/product/learning-typescript-enhance-your-web-development- skills-using-type-safe-javascript-44538720 ebooknice.com (Ebook) Large Scale Apps with React and TypeScript by Damiano Fusco https://ebooknice.com/product/large-scale-apps-with-react-and- typescript-47843004 ebooknice.com (Ebook) Large Scale Apps with Svelte and TypeScript by Damiano Fusco https://ebooknice.com/product/large-scale-apps-with-svelte-and- typescript-47843144 ebooknice.com (Ebook) Large Scale Apps with Vue, Vite and TypeScript by Damiano Fusco https://ebooknice.com/product/large-scale-apps-with-vue-vite-and- typescript-47843306 ebooknice.com
  • 6.
    1. Preface a. HowThis Book Is Organized b. Style i. Conventions Used in This Book c. Using Code Examples d. O’Reilly Online Learning e. How to Contact Us f. Acknowledgments 2. 1. Introduction 3. 2. TypeScript: A 10_000 Foot View a. The Compiler b. The Type System i. TypeScript Versus JavaScript c. Code Editor Setup i. tsconfig.json ii. tslint.json d. index.ts e. Exercises 4. 3. All About Types a. Talking About Types b. The ABCs of Types
  • 7.
    i. any ii. unknown iii.boolean iv. number v. bigint vi. string vii. symbol viii. Objects ix. Intermission: Type Aliases, Unions, and Intersections x. Arrays xi. Tuples xii. null, undefined, void, and never xiii. Enums c. Summary d. Exercises 5. 4. Functions a. Declaring and Invoking Functions i. Optional and Default Parameters ii. Rest Parameters iii. call, apply, and bind iv. Typing this v. Generator Functions
  • 8.
    vi. Iterators vii. CallSignatures viii. Contextual Typing ix. Overloaded Function Types b. Polymorphism i. When Are Generics Bound? ii. Where Can You Declare Generics? iii. Generic Type Inference iv. Generic Type Aliases v. Bounded Polymorphism vi. Generic Type Defaults c. Type-Driven Development d. Summary e. Exercises 6. 5. Classes and Interfaces a. Classes and Inheritance b. super c. Using this as a Return Type d. Interfaces i. Declaration Merging ii. Implementations iii. Implementing Interfaces Versus Extending Abstract Classes
  • 9.
    e. Classes AreStructurally Typed f. Classes Declare Both Values and Types g. Polymorphism h. Mixins i. Decorators j. Simulating final Classes k. Design Patterns i. Factory Pattern ii. Builder Pattern l. Summary m. Exercises 7. 6. Advanced Types a. Relationships Between Types i. Subtypes and Supertypes ii. Variance iii. Assignability iv. Type Widening v. Refinement b. Totality c. Advanced Object Types i. Type Operators for Object Types ii. The Record Type
  • 10.
    iii. Mapped Types iv.Companion Object Pattern d. Advanced Function Types i. Improving Type Inference for Tuples ii. User-Defined Type Guards e. Conditional Types i. Distributive Conditionals ii. The infer Keyword iii. Built-in Conditional Types f. Escape Hatches i. Type Assertions ii. Nonnull Assertions iii. Definite Assignment Assertions g. Simulating Nominal Types h. Safely Extending the Prototype i. Summary j. Exercises 8. 7. Handling Errors a. Returning null b. Throwing Exceptions c. Returning Exceptions d. The Option Type
  • 11.
    e. Summary f. Exercises 9.8. Asynchronous Programming, Concurrency, and Parallelism a. JavaScript’s Event Loop b. Working with Callbacks c. Regaining Sanity with Promises d. async and await e. Async Streams i. Event Emitters f. Typesafe Multithreading i. In the Browser: With Web Workers ii. In NodeJS: With Child Processes g. Summary h. Exercises 10. 9. Frontend and Backend Frameworks a. Frontend Frameworks i. React ii. Angular 6/7 b. Typesafe APIs c. Backend Frameworks d. Summary
  • 12.
    11. 10. Namespaces.Modules a.A Brief History of JavaScript Modules b. import, export i. Dynamic Imports ii. Using CommonJS and AMD Code iii. Module Mode Versus Script Mode c. Namespaces i. Collisions ii. Compiled Output d. Declaration Merging e. Summary f. Exercise 12. 11. Interoperating with JavaScript a. Type Declarations i. Ambient Variable Declarations ii. Ambient Type Declarations iii. Ambient Module Declarations b. Gradually Migrating from JavaScript to TypeScript i. Step 1: Add TSC ii. Step 2a: Enable Typechecking for JavaScript (Optional)
  • 13.
    iii. Step 2b:Add JSDoc Annotations (Optional) iv. Step 3: Rename Your Files to .ts v. Step 4: Make It strict c. Type Lookup for JavaScript d. Using Third-Party JavaScript i. JavaScript That Comes with Type Declarations ii. JavaScript That Has Type Declarations on DefinitelyTyped iii. JavaScript That Doesn’t Have Type Declarations on DefinitelyTyped e. Summary 13. 12. Building and Running TypeScript a. Building Your TypeScript Project i. Project Layout ii. Artifacts iii. Dialing In Your Compile Target iv. Enabling Source Maps v. Project References vi. Error Monitoring b. Running TypeScript on the Server c. Running TypeScript in the Browser d. Publishing Your TypeScript Code to NPM
  • 14.
    e. Triple-Slash Directives i.The types Directive ii. The amd-module Directive f. Summary 14. 13. Conclusion 15. A. Type Operators 16. B. Type Utilities 17. C. Scoped Declarations a. Does It Generate a Type? b. Does It Merge? 18. D. Recipes for Writing Declaration Files for Third- Party JavaScript Modules a. Types of Exports i. Globals ii. ES2015 Exports iii. CommonJS Exports iv. UMD Exports b. Extending a Module i. Globals ii. Modules 19. E. Triple-Slash Directives a. Internal Directives
  • 15.
    b. Deprecated Directives 20.F. TSC Compiler Flags for Safety 21. G. TSX 22. Index
  • 16.
    Programming TypeScript Making YourJavaScript Applications Scale Boris Cherny
  • 17.
    Programming TypeScript by BorisCherny Copyright © 2019 Boris Cherny. 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 corporate@oreilly.com.
  • 18.
    Development Editor: AngelaRufino Indexer: Margaret Troutman Acquisitions Editor: Jennifer Pollock Interior Designer: David Futato Production Editor: Katherine Tozer Cover Designer: Karen Montgomery Copyeditor: Rachel Head Illustrator: Rebecca Demarest Proofreader: Charles Roumeliotis May 2019: First Edition Revision History for the First Edition 2019-04-18: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492037651 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming TypeScript, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
  • 19.
    The views expressedin 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-492-03765-1 [LSI]
  • 20.
    Dedication To Sasha andMichael, who might also fall in love with types, someday.
  • 21.
    Preface This is abook for programmers of all walks: professional JavaScript engineers, C# people, Java sympathizers, Python lovers, Ruby aficionados, Haskell nerds. Whatever language(s) you write in, so long as you have some experience programming and know the basics of functions, variables, classes, and errors, this book is for you. Some experience with JavaScript, including a basic knowledge of the Document Object Model (DOM) and the network, will help you along the way—while we don’t dive deep into these concepts, they are a wellspring of excellent examples, and if you’re not familiar with them the examples might not make as much sense. Regardless of what programming languages you’ve used in the past, what unites all of us is our shared experience of tracking down exceptions, tracing through code line by line to figure out what went wrong and how we can fix it. This is the experience that TypeScript helps prevent by examining your code automatically and pointing out the mistakes you may have missed. It’s OK if you haven’t worked with a statically typed language before. I’ll teach you about types and how to use them effectively to make your programs crash less, document your
  • 22.
    code better, andscale your applications across more users, engineers, and servers. I’ll try to avoid big words when I can, and explain ideas in a way that’s intuitive, memorable, and practical, using lots of examples along the way to help keep things concrete. That’s the thing about TypeScript: unlike a lot of other typed languages, TypeScript is intensely practical. It invents completely new concepts so you can speak more concisely and precisely, letting you write applications in a way that’s fun, modern, and safe.
  • 23.
    How This BookIs Organized This book has two aims: to give you a deep understanding of how the TypeScript language works (theory) and provide bucketfuls of pragmatic advice about how to write production TypeScript code (practice). Because TypeScript is such a practical language, theory quickly turns to practice, and most of this book ends up being a mix of the two, with the first couple of chapters almost entirely theory, and the last few almost completely practice. I’ll start with the basics of what compilers, typecheckers, and types are. I’ll then give a broad overview of the different types and type operators in TypeScript, what they’re for, and how you use them. Using what we’ve learned, I’ll cover some advanced topics like TypeScript’s most sophisticated type system features, error handling, and asynchronous programming. Finally, I’ll wrap up with how to use TypeScript with your favorite frameworks (frontend and backend), migrating your existing JavaScript project to TypeScript, and running your TypeScript application in production. Most chapters come with a set of exercises at the end. Try to do these yourself—they’ll give you a deeper intuition for what we cover than just reading would. Answers for chapter exercises are available online, at https://github.com/bcherny/programming-typescript-answers.
  • 24.
    Style Throughout this book,I tried to stick to a single code style. Some aspects of this style are deeply personal—for example: I only use semicolons when necessary. I indent with two spaces. I use short variable names like a, f, or _ where the program is a quick snippet, or where the structure of the program is more important than the details. Some aspects of the code style, however, are things that I think you should do too. A few of these are: You should use the latest JavaScript syntax and features (the latest JavaScript version is usually just called “esnext”). This will keep your code in line with the latest standards, improving interoperability and Googleability, and it can help reduce ramp-up time for new hires. It also lets you take advantage of powerful, modern JavaScript features like arrow functions, promises, and generators. You should keep your data structures immutable with spreads (...) most of the time. You should make sure everything has a type, inferred when possible. Be careful not to abuse explicit types; 1
  • 25.
    this will helpkeep your code clear and terse, and improve safety by surfacing incorrect types rather than bandaiding over them. You should keep your code reusable and generic. Polymorphism (see “Polymorphism”) is your best friend. Of course, these ideas are hardly new. But TypeScript works especially well when you stick to them. TypeScript’s built-in downlevel compiler, support for read-only types, powerful type inference, deep support for polymorphism, and completely structural type system encourage good coding style, while the language remains incredibly expressive and true to the underlying JavaScript. A couple more notes before we begin. JavaScript doesn’t expose pointers and references; instead it has value and reference types. Values are immutable, and include things like strings, numbers, and booleans, while references point to often-mutable data structures like arrays, objects, and functions. When I use the word “value” in this book, I usually mean it loosely to refer to either a JavaScript value or a reference. Lastly, you might find yourself writing less-than-ideal TypeScript code in the wild when interoperating with JavaScript, or incorrectly typed third-party libraries, or legacy code, or if you’re in a rush. This book largely presents how you
  • 26.
    should write TypeScript,and makes an argument for why you should try really hard not to make compromises. But in practice, how correct your code is is up to you and your team. 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, environment variables, statements, and keywords. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP This element signifies a tip or suggestion.
  • 27.
    NOTE This element signifiesa 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://github.com/bcherny/programming-typescript-answers. 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 a CD-ROM of 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.
  • 28.
    We appreciate, butdo not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming TypeScript by Boris Cherny (O’Reilly). Copyright 2019 Boris Cherny, 978-1-492-03765-1.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For almost 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, conferences, 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, please visit http://oreilly.com.
  • 29.
    How to ContactUs 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/programming-typescript. To comment or ask technical questions about this book, send email to bookquestions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia
  • 30.
    Acknowledgments This book isthe product of years’ worth of snippets and doodles, followed by a year’s worth of early mornings and nights and weekends and holidays spent writing. Thank you to O’Rielly for the opportunity to work on this book, and to my editor Angela Rufino for the support throughout the process. Thank you to Nick Nance for his contribution in “Typesafe APIs”, and to Shyam Seshadri for his contribution in “Angular 6/7”. Thanks to my technical editors: Daniel Rosenwasser of the TypeScript team, who spent an unreasonable amount of time reading through this manuscript and guiding me through the nuances of TypeScript’s type system, and Jonathan Creamer, Yakov Fain, and Paul Buying, and Rachel Head for technical edits and feedback. Thanks to my family—Liza and Ilya, Vadim, Roza and Alik, Faina and Yosif —for encouraging me to pursue this project. Most of all, thanks to my partner Sara Gilford, who supported me throughout the writing process, even when it meant calling off weekend plans, late nights writing and coding, and far too many unprompted conversations about the ins and outs of type systems. I couldn’t have done it without you, and I’m forever grateful for your support. 1 If you’re not coming from JavaScript, here’s an example: if you have an object o, and you want to add a property k to it with the value 3, you can either mutate o directly—o.k = 3—or you can apply your
  • 31.
    change to o,creating a new object as a result—let p = {...o, k: 3}.
  • 32.
    Chapter 1. Introduction So,you decided to buy a book about TypeScript. Why? Maybe it’s because you’re sick of those weird cannot read property blah of undefined JavaScript errors. Or maybe you heard TypeScript can help your code scale better, and wanted to see what all the fuss is about. Or you’re a C# person, and have been thinking of trying out this whole JavaScript thing. Or you’re a functional programmer, and decided it was time to take your chops to the next level. Or your boss was so fed up with your code causing production issues that they gave you this book as a Christmas present (stop me if I’m getting warm). Whatever your reasons are, what you’ve heard is true. TypeScript is the language that will power the next generation of web apps, mobile apps, NodeJS projects, and Internet of Things (IoT) devices. It will make your programs safer by checking for common mistakes, serve as documentation for yourself and future engineers, make refactoring painless, and make, like, half of your unit tests unnecessary (“What unit tests?”). TypeScript will double your productivity as a programmer, and it will land you a date with that cute barista across the street.
  • 33.
    But before yougo rushing across the street, let’s unpack all of that a little bit, starting with this: what exactly do I mean when I say “safer”? What I am talking about, of course, is type safety. TYPE SAFETY Using types to prevent programs from doing invalid things. Here are a few examples of things that are invalid: Multiplying a number and a list Calling a function with a list of strings when it actually needs a list of objects Calling a method on an object when that method doesn’t actually exist on that object Importing a module that was recently moved There are some programming languages that try to make the most of mistakes like these. They try to figure out what you really meant when you did something invalid, because hey, you do what you can, right? Take JavaScript, for example: 3 + [] // Evaluates to the string "3" let obj = {} obj.foo // Evaluates to undefined 1
  • 34.
    function a(b) { returnb/2 } a("z") // Evaluates to NaN Notice that instead of throwing exceptions when you try to do things that are obviously invalid, JavaScript tries to make the best of it and avoids exceptions whenever it can. Is JavaScript being helpful? Certainly. Does it make it easier for you to catch bugs quickly? Probably not. Now imagine if JavaScript threw more exceptions instead of quietly making the best of what we gave it. We might get feedback like this instead: 3 + [] // Error: Did you really mean to ad let obj = {} obj.foo // Error: You forgot to define the function a(b) { return b/2 } a("z") // Error: The function "a" expects // but you gave it a string. Don’t get me wrong: trying to fix our mistakes for us is a neat feature for a programming language to have (if only it worked
  • 35.
    for more thanjust programs!). But for JavaScript, this feature creates a disconnect between when you make a mistake in your code, and when you find out that you made a mistake in your code. Often, that means that the first time you hear about your mistake will be from someone else. So here’s a question: when exactly does JavaScript tell you that you made a mistake? Right: when you actually run your program. Your program might get run when you test it in a browser, or when a user visits your website, or when you run a unit test. If you’re disciplined and write plenty of unit tests and end-to-end tests, smoke test your code before pushing it, and test it internally for a while before shipping it to users, you will hopefully find out about your error before your users do. But what if you don’t? That’s where TypeScript comes in. Even cooler than the fact that TypeScript gives you helpful error messages is when it gives them to you: TypeScript gives you error messages in your text editor, as you type. That means you don’t have to rely on unit tests or smoke tests or coworkers to catch these sorts of issues: TypeScript will catch them for you and warn you about them as you write your program. Let’s see what TypeScript says about our previous example: 3 + [] // Error TS2365: Operator '+' canno // and 'never[]'.
  • 36.
    let obj ={} obj.foo // Error TS2339: Property 'foo' doe function a(b: number) { return b / 2 } a("z") // Error TS2345: Argument of type ' // parameter of type 'number'. In addition to eliminating entire classes of type-related bugs, this will actually change the way you write code. You will find yourself sketching out a program at the type level before you fill it in at the value level; you will think about edge cases as you design your program, not as an afterthought; and you will design programs that are simpler, faster, easier to understand, and easier to maintain. Are you ready to begin the journey? Let’s go! 1 Depending on which statically typed language you use, “invalid” can mean a range of things, from programs that will crash when you run them to things that won’t crash but are clearly nonsensical. 2 If you’re not sure what “type level” means here, don’t worry. We’ll go over it in depth in later chapters. 2
  • 37.
    Chapter 2. TypeScript:A 10_000 Foot View Over the next few chapters, I’ll introduce the TypeScript language, give you an overview of how the TypeScript Compiler (TSC) works, and take you on a tour of TypeScript’s features and the patterns you can develop with them. We’ll start with the compiler. The Compiler Depending on what programming languages you worked with in the past (that is, before you decided to buy this book and commit to a life of type safety), you’ll have a different understanding of how programs work. The way TypeScript works is unusual compared to other mainstream languages like JavaScript or Java, so it’s important that we’re on the same page before we go any further. Let’s start broad: programs are files that contain a bunch of text written by you, the programmer. That text is parsed by a special program called a compiler, which transforms it into an abstract syntax tree (AST), a data structure that ignores things like whitespace, comments, and where you stand on the tabs versus spaces debate. The compiler then converts that AST to
  • 38.
    a lower-level representationcalled bytecode. You can feed that bytecode into another program called a runtime to evaluate it and get a result. So when you run a program, what you’re really doing is telling the runtime to evaluate the bytecode generated by the compiler from the AST parsed from your source code. The details vary, but for most languages this is an accurate high-level view. Once again, the steps are: 1. Program is parsed into an AST. 2. AST is compiled to bytecode. 3. Bytecode is evaluated by the runtime. Where TypeScript is special is that instead of compiling straight to bytecode, TypeScript compiles to… JavaScript code! You then run that JavaScript code like you normally would—in your browser, or with NodeJS, or by hand with a paper and pen (for anyone reading this after the machine uprising has begun). At this point you may be thinking: “Wait! In the last chapter you said TypeScript makes my code safer! When does that happen?” Great question. I actually skipped over a crucial step: after the TypeScript Compiler generates an AST for your program—but before it emits code—it typechecks your code.
  • 39.
    TYPECHECKER A special programthat verifies that your code is typesafe. This typechecking is the magic behind TypeScript. It’s how TypeScript makes sure that your program works as you expect, that there aren’t obvious mistakes, and that the cute barista across the street really will call you back when they said they would. (Don’t worry, they’re probably just busy.) So if we include typechecking and JavaScript emission, the process of compiling TypeScript now looks roughly like Figure 2-1: Figure 2-1. Compiling and running TypeScript
  • 40.
    Steps 1–3 aredone by TSC, and steps 4–6 are done by the JavaScript runtime that lives in your browser, NodeJS, or whatever JavaScript engine you’re using. NOTE JavaScript compilers and runtimes tend to be smushed into a single program called an engine; as a programmer, this is what you’ll normally interact with. It’s how V8 (the engine powering NodeJS, Chrome, and Opera), SpiderMonkey (Firefox), JSCore (Safari), and Chakra (Edge) work, and it’s what gives JavaScript the appearance of being an interpreted language. In this process, steps 1–2 use your program’s types; step 3 does not. That’s worth reiterating: when TSC compiles your code from TypeScript to JavaScript, it won’t look at your types. That means your program’s types will never affect your program’s generated output, and are only used for typechecking. This feature makes it foolproof to play around with, update, and improve your program’s types, without risking breaking your application. The Type System Modern languages have all sorts of different type systems.
  • 41.
    TYPE SYSTEM A setof rules that a typechecker uses to assign types to your program. There are generally two kinds of type systems: type systems in which you have to tell the compiler what type everything is with explicit syntax, and type systems that infer the types of things for you automatically. Both approaches have trade-offs. TypeScript is inspired by both kinds of type systems: you can explicitly annotate your types, or you can let TypeScript infer most of them for you. To explicitly signal to TypeScript what your types are, use annotations. Annotations take the form value: type and tell the typechecker, “Hey! You see this value here? Its type is type.” Let’s look at a few examples (the comments following each line are the actual types inferred by TypeScript): let a: number = 1 // a is a number let b: string = 'hello' // b is a string let c: boolean[] = [true, false] // c is an array of And if you want TypeScript to infer your types for you, just leave them off and let TypeScript get to work: let a = 1 // a is a number let b = 'hello' // b is a string 1
  • 42.
    let c =[true, false] // c is an array of Right away, you’ll notice how good TypeScript is at inferring types for you. If you leave off the annotations, the types are the same! Throughout this book, we will use annotations only when necessary, and let TypeScript work its inference magic for us whenever possible. NOTE In general, it is good style to let TypeScript infer as many types as it can for you, keeping explicitly typed code to a minimum. TypeScript Versus JavaScript Let’s take a deeper look at TypeScript’s type system, and how it compares to JavaScript’s type system. Table 2-1 presents an overview. A good understanding of the differences is key to building a mental model of how TypeScript works.
  • 43.
    Table 2-1. ComparingJavaScript’s and TypeScript’s type systems Type system feature JavaScript TypeScript How are types bound? Dynamically Statically Are types automatically converted? Yes No (mostly) When are types checked? At runtime At compile time When are errors surfaced? At runtime (mostly) At compile time (mostly) HOW ARE TYPES BOUND? Dynamic type binding means that JavaScript needs to actually run your program to know the types of things in it. JavaScript doesn’t know your types before running your program. TypeScript is a gradually typed language. That means that TypeScript works best when it knows the types of everything in your program at compile time, but it doesn’t have to know every type in order to compile your program. Even in an untyped program TypeScript can infer some types for you and catch some mistakes, but without knowing the types for
  • 44.
    everything, it willlet a lot of mistakes slip through to your users. This gradual typing is really useful for migrating legacy codebases from untyped JavaScript to typed TypeScript (more on that in “Gradually Migrating from JavaScript to TypeScript”), but unless you’re in the middle of migrating your codebase, you should aim for 100% type coverage. That is the approach this book takes, except where explicitly noted. ARE TYPES AUTOMATICALLY CONVERTED? JavaScript is weakly typed, meaning if you do something invalid like add a number and an array (like we did in Chapter 1), it will apply a bunch of rules to figure out what you really meant so it can do the best it can with what you gave it. Let’s walk through the specific example of how JavaScript evaluates 3 + [1]: 1. JavaScript notices that 3 is a number and [1] is an array. 2. Because we’re using +, it assumes we want to concatenate the two. 3. It implicitly converts 3 to a string, yielding "3". 4. It implicitly converts [1] to a string, yielding "1". 5. It concatenates the results, yielding "31".
  • 45.
    We could dothis more explicitly too (so JavaScript avoids doing steps 1, 3, and 4): 3 + [1]; // evaluates to "31" (3).toString() + [1].toString() // evaluates to "31" While JavaScript tries to be helpful by doing clever type conversions for you, TypeScript complains as soon as you do something invalid. When you run that same JavaScript code through TSC, you’ll get an error: 3 + [1]; // Error TS2365: Ope // types '3' and 'nu (3).toString() + [1].toString() // evaluates to "31" If you do something that doesn’t seem right, TypeScript complains, and if you’re explicit about your intentions, TypeScript gets out of your way. This behavior makes sense: who in their right mind would try to add a number and an array, expecting the result to be a string (of course, besides Bavmorda the JavaScript witch who spends her time coding by candlelight in your startup’s basement)? The kind of implicit conversion that JavaScript does can be a really hard-to-track-down source of errors, and is the bane of
  • 46.
    many JavaScript programmers.It makes it hard for individual engineers to get their jobs done, and it makes it even harder to scale code across a large team, since every engineer needs to understand the implicit assumptions your code makes. In short, if you must convert types, do it explicitly. WHEN ARE TYPES CHECKED? In most places JavaScript doesn’t care what types you give it, and it instead tries to do its best to convert what you gave it to what it expects. TypeScript, on the other hand, typechecks your code at compile time (remember step 2 in the list at the beginning of this chapter?), so you don’t need to actually run your code to see the Error from the previous example. TypeScript statically analyzes your code for errors like these, and shows them to you before you run it. If your code doesn’t compile, that’s a really good sign that you made a mistake and you should fix it before you try to run the code. Figure 2-2 shows what happens when I type the last code example into VSCode (my code editor of choice).
  • 47.
    Figure 2-2. TypeErrorreported by VSCode With a good TypeScript extension for your preferred code editor, the error will show up as a red squiggly line under your code as you type it. This dramatically speeds up the feedback loop between writing code, realizing that you made a mistake, and updating the code to fix that mistake. WHEN ARE ERRORS SURFACED? When JavaScript throws exceptions or performs implicit type conversions, it does so at runtime. This means you have to actually run your program to get a useful signal back that you did something invalid. In the best case, that means as part of a unit test; in the worst case, it means an angry email from a user. TypeScript throws both syntax-related errors and type-related errors at compile time. In practice, that means those kinds of errors will show up in your code editor, right as you type—it’s 2
  • 48.
    an amazing experienceif you’ve never worked with an incrementally compiled statically typed language before. That said, there are lots of errors that TypeScript can’t catch for you at compile time—things like stack overflows, broken network connections, and malformed user inputs—that will still result in runtime exceptions. What TypeScript does is make compile-time errors out of most errors that would have otherwise been runtime errors in a pure JavaScript world. Code Editor Setup Now that you have some intuition for how the TypeScript Compiler and type system work, let’s get your code editor set up so we can start diving into some real code. Start by downloading a code editor to write your code in. I like VSCode because it provides a particularly nice TypeScript editing experience, but you can also use Sublime Text, Atom, Vim, WebStorm, or whatever editor you like. Engineers tend to be really picky about IDEs, so I’ll leave it to you to decide. If you do want to use VSCode, follow the instructions on the website to get it set up. TSC is itself a command-line application written in TypeScript, which means you need NodeJS to run it. Follow the instructions on the official NodeJS website to get NodeJS up and running on your machine. 3 4
  • 49.
    NodeJS comes withNPM, a package manager that you will use to manage your project’s dependencies and orchestrate your build. We’ll start by using it to install TSC and TSLint (a linter for TypeScript). Start by opening your terminal and creating a new folder, then initializing a new NPM project in it: # Create a new folder mkdir chapter-2 cd chapter-2 # Initialize a new NPM project (follow the prompts) npm init # Install TSC, TSLint, and type declarations for Node npm install --save-dev typescript tslint @types/node tsconfig.json Every TypeScript project should include a file called tsconfig.json in its root directory. This tsconfig.json is where TypeScript projects define things like which files should be compiled, which directory to compile them to, and which version of JavaScript to emit. Create a new file called tsconfig.json in your root folder (touch tsconfig.json), then pop it open in your code editor and give it the following contents: 5
  • 50.
    Random documents withunrelated content Scribd suggests to you:
  • 51.
    Quickly turning hishorse’s head, the sturdy borderer ordered his troop to proceed eastward. “Don’t act too rashly, Captain,” entreated Penn. “General Braddock is ignorant of this country and Indian methods of warfare. He may have orders not to enlist native troops, yet without your aid I fear for the success of his expedition. Please let me intercede with him; he will do it when he hears that I am your friend.” “To the devil with him and his kind, the swinish snob,” growled Captain Jack, while his black eyes flashed a diabolical hatred; his Spanish temper was uncontrollable. That night, when Captain Jack and John Penn were seated at their camp fire at Laurel Run, a messenger, a Major, not a Sergeant Major, from General Braddock was announced. Saluting, the officer asked to be allowed to speak with John Penn, Esquire. Penn received the officer without rising, and was cooly civil throughout the interview, which consisted principally of reading a letter from Braddock, expressing deep regret “that he had not known that the son of his dear friend, Richard Penn, had been with –-- Jack,” and offering Penn the captaincy of Black Jack’s company of scouts, “–-- Jack to be First Lieutenant.” Naturally, Captain Jack was more enraged than ever, but he said: “Take it, John, I’ll withdraw and turn my men, who, you know, are the best shots in the Province, over to you. They would go through hell for you.” “Never fear,” replied Penn, and, turning to the Major, he said: “Tell General Braddock, with my compliments, that I decline to accept a commission which he has no authority to tender. As for my companion, Captain Jack (laying emphasis on the Captain) the General had his decision earlier in the day. Goodnight, Major.” Thus terminated the “conference” which might have changed the face of history. As the result of Braddock’s pride and folly, his defeat and death are a part of history, known by every Pennsylvanian. John Penn was wretchedly unhappy, even though Captain Jack tried to console him, when he shrewdly inferred that “Mary” had been kidnapped by emissaries of his relatives, and had not eloped with a vile serving man. His heart was too lacerated to remain longer
  • 52.
    with the WildHunter, now that no active service was to be experienced; so, accompanied by Monkton, the veteran of Preston, he set out the next morning for the West Branch of the Susquehanna to the unexplored countries. At Waterford Narrows they passed the body of a trader recently killed and scalped by Indians. “May I draw one of his teeth, sir?” said the old soldier, “and you can carry it in your pocket, for the old people say ‘The only thing that can break the enchantment of love is the tooth of a dead man’.” Penn shook his head and rode on. For a considerable time Penn and Old Monkton visited with Dagonando (Rock Pine), a noted Indian Chief in Brush Valley (Centre County), for the young man, like the founder of Pennsylvania, possessed the same irresistible charm over the redmen. Years afterwards, in Philadelphia, speaking to General Thomas Mifflin, Dagonando stated that had it not been for his unhappy love affairs, John Penn would have been the equal of his grandfather as Governor, and prevented the Revolutionary War. But his spirit was crushed; even a mild love affair with Dagonando’s daughter ended with shocking disaster. Reaching Fort Augusta, Penn became very ill; a “nervous breakdown” his ailment would be diagnosed today. During his illness he was robbed of his diary. He reached Philadelphia in the fall, and almost immediately set sail for England. He remained abroad until 1763, when he returned as Governor of Pennsylvania. He arrived in Philadelphia on October 30, in the midst of the terrific earthquake of that year, and on November 5, George Roberts in a letter to Samuel Powell, in describing the new Chief Magistrate, says: “His Honor, Penn, is a little gentleman, though he may govern equal to one seven feet high.” Charles P. Keith has thus summed up Penn’s career from the time of his first arrival in Pennsylvania: “He was one of the Commissioners to the Congress at Albany in the summer of 1754, and made several journeys to the neighboring colonies. Nevertheless, his trouble made him again despondent; he began to shun company; he would have joined Braddock’s army had any
  • 53.
    Pennsylvania troops formedpart of it, and perhaps have died on the field which that officer’s imprudence made so disastrous. Some two months after the defeat he returned to England.” On June 6, 1766, a brilliant marriage occurred in Philadelphia. John Penn, Lieutenant Governor, aged thirty-seven years, married Anne, the daughter of William Allen, Chief Justice; a strange fate had united the relative of Peter Allen of “Tulliallan” to the husband of Maria Cox, pronounced legally dead after an absence of eleven years in parts unknown. Commenting on this alliance, Nevin Moyer, the gifted Historian, remarks: “The marriage was an unpleasant one, on his (Penn’s) account, for he was found very seldom at home.” It was during the wedding that a fierce electrical storm occurred, unroofing houses and shattering many old trees. It was not long after this marriage when a feeling of restlessness impelled him to start another of his many trips to the interior. This time it was given out that he wished to visit Penn’s Valley, the “empire” discovered in the central part of the province by Captains Potter and Thompson, and named in his honor, and Penn’s Cave, the source of the Karoondinha, a beautiful, navigable stream, rechristened “John Penn’s Creek.” He managed to stop over night, as everyone of any consequence did, at “Tulliallan,” and slept in the room with the Scotch thistles carved on the woodwork, and saw Peter Allen for the first time in twelve years. A foul crime had recently been committed in the neighborhood. Indian Joshua, who used to live at the running spring, had gone to Canada the year of Braddock’s defeat (the year of Mary’s disappearance, Penn always reckoned it) and had lately returned to his old abode. He had been shot, as a trail of blood from his cabin down the mountain had been followed clear to Clark’s Creek, where it was lost. In fact, pitiful wailing had been heard one night all the way across the valley, but it was supposed to be a traveling panther. Arvas, or Silver Heels, had also come back for a time, but, after Joshua’s disappearance, had gone away. “Maybe he killed his friend,” whispered Allen, looking down guiltily, as he spoke what he knew to be untruthful words.
  • 54.
    “It is allclear to me now, Allen,” said Penn. “I should have believed Captain Jack, when in ’55 he told me that my late wife was carried off to Canada by Indians; the kidnappers came back, and for fear that they would levy hush money on those who had caused my Mary to be stolen, murdered Joshua as a warning.” Allen did not answer, but Penn said: “You have kept a public house so long that you have forgotten to be a gentleman, and I do not expect you to tell the truth.” In 1840 seekers after nestlings of the vultures climbed to the top of the King’s Stool, the dizzy pinnacle of the Third Mountain. There they found the skeleton of an Indian. It was all that was left of Joshua, who had climbed there in his agony and died far above the scenes which he loved so dearly. The hunters put the bones in their hunting pouches and climbed down the “needle,” and buried them decently at the foot of the rocks. The King’s Stool is named for a similar high point near Lough Foyle, Ireland, and there are also King’s Stools in Juniata and Perry Counties. The North of Ireland pioneers were glad to recognize scenes similar to the natural wonders of the Green Isle! A great light had come to John Penn, but he accepted his fate philosophically, just as he had the abuse heaped upon him for his vacillating policy towards the Indians. He followed up his vigorous attempt to punish the Paxtang perpetrators of the massacres of the Conestoga Indians at Christmas time, 1763, by promulgating the infamous scalp bounty of July, 1764, which bounty, to again quote Professor Moyer, paid “$134 for an Indian’s scalp, and $150 for a live Indian, and $50 for an Indian female or child’s scalp.” There are not enough Indians to make hunting for bounties in Pennsylvania a paying occupation today, so instead there is a bounty on Wildcats and foxes, wiping out desirable wild life to satisfy the politicians’ filthy greed. John Penn returned to Philadelphia without visiting Penn’s Valley or Penn’s Cave or John Penn’s Creek. He had seen them previously in 1755 when they bore their original Indian names, and his heart was still sad. It was not long after returning that he again started on another expedition up the Susquehanna, traveling by canoe, just as
  • 55.
    his grandfather, WilliamPenn, had done in his supposedly fabulous trip to the sources of the West Branch at Cherry Tree, in 1700. A stop was made at Fisher’s stone house, Fisher’s Ferry. A group of pioneers had heard of his coming and gave the little Governor a rousing ovation. He felt nearest to being happy when among the frontier people, who understood him, and his trials had, like Byron, made him “the friend of mountains”; he was still simple at heart. In the kitchen, seated by the inglenook, he heard someone’s incessant coughing in an inner room. He asked the landlord, old Peter Fisher, who was suffering so acutely. “Why, sir,” replied Fisher, “it’s an Englishwoman dying.” In those days people’s nationalities in Pennsylvania were more sharply defined, and any English-speaking person was always called an “Englishwoman” or an “Englishman,” as the case might be. “Tell me about her,” said the Governor, with ill-concealed curiosity. “It’s a strange story, it might give Your Worship offense,” faltered the old innkeeper. “They tell it, sir, though it’s doubtless a lie, that Your Excellency cared for this Englishwoman, and your enemies had her kidnapped by two Indians and taken to Canada. The Indians were paid for keeping her there until a few years ago, when their remittances suddenly stopped and they came home; one, it is said, was murdered soon after. Arvas, his companion, was accused of the crime, but he stopped here for a night, a few weeks afterwards, and swore to me that he was guiltless. The Englishwoman finally got away and walked all the way back from a place called Muskoka, but she caught cold and consumption on the way, and is on her death- bed now. I knew her in all her youth and beauty at Peter Allen’s, where she was always the belle of the balls there; she had been brought up a Quaker, but my, how she could dance. You would not know her now.” “I want to see her,” said the Governor, rising to his feet. It was getting dark, so Fisher lit a rushlight, and led the way. He opened the heavy door without rapping. His wife and daughter sat on high-backed rush-bottomed chairs on either side of the big four- poster bed, which had come from the Rhine country. On the bed lay a woman of about forty years, frightfully emaciated by suffering,
  • 56.
    whose exaggeratedly clear-cutfeatures were accentuated in their marble look by the pallor of oncoming dissolution. Her wavy, dark hair, parted in the middle, made her face seem even whiter. “Mary, Mary,” said the little Governor, as he ran to her side, seizing the white hands which lay on the flowered coverlet. “John, my darling John,” gasped the dying woman. “Leave us alone together,” commanded the Governor. The women looked at one another as they retired. The thoughts which their glances carried indicated “well, after all the story’s true.” They had been alone for about ten minutes when Penn ran out of the door calling, “Come quick, someone, I fear she’s going.” The household speedily assembled, but in another ten minutes “Mary Warren,” alias Maria Cox-Penn had yielded up the ghost. She is buried on the brushy African-looking hillside which faces the “dreamy Susquehanna,” the Firestone Mountains and the sunset, near where travelers across Broad Mountain pass every day. John Penn returned to Philadelphia and took no more trips to the interior. He divided his time between his town house, 44 Pine Street, and his country seat “Lansdowne.” During the Revolution he was on parole. He died childless. February 9, 1795, and is said to be buried under the floor, near the chancel, in the historic Christ Church, Philadelphia, which bears the inscription that he was “One of the Late Proprietors of Pennsylvania.” Most probably his body was later taken to England. His wife, nee Allen, survived him until 1813. The other night in the grand hall of the Historical Society of Pennsylvania in the Quaker City, a notable reception was given in honor of the grand historian-governor, William C. Sproul, fresh from his marvelous restoration of the Colonial Court House at Chester. As he stood there, the embodiment of mental and physical grace and strength, the greatest Governor of a generation, receiving the long line of those who came to pay their respects and well wishes, Albert Cook Myers, famed historian of the Quakers, mentioned that the present Governor of the Commonwealth was standing just beneath the portrait of John Penn, one of the last of the Proprietaries. And what a contrast there was! Penn looked so effete and almost
  • 57.
    feminine with hischild-like blonde locks, his pink cheeks, weak, half- closed mouth, his slender form in a red coat, so different from the vigorous living Governor. Penn was also so inferior to the other notable portraits which hung about him–the sturdy Huguenot, General Henri Bouquet, the deliverer of Fort Duquesne in 1758 and 1763; the stalwart Scot, General Arthur St. Clair, of Miami fame, who was left to languish on a paltry pension of $180 a year at his rough, rocky farm on Laurel Ridge; the courageous-looking Irishman, General Edward Hand; and, above all, the bold and dashing eagle face of General “Mad Anthony” Wayne. Such company for the last of the Penns to keep! Though lacking the manly outlines of his fellows on canvas, who can say that his life had one whit less interest than theirs–probably much more so, for his spirit had felt the thrill of an undying love, which in the end surmounted all difficulties and left his heart master of the field. Though his record for statecraft can hardly be written from a favorable light, and few of his sayings or deeds will live, he has joined an immortal coterie led down the ages by Anthony and the beautiful Egyptian queen, by Abelard and Heloise, Dante and Beatrice, Petrarch and Laura, Alfieri and the Countess of Albany, and here in Pennsylvania by Hugh H. Brackenridge and the pioneer girl, Sabina Wolfe, and Elisha Kent Kane, and the spiritualist, Maria Fox. Love is a force that is all-compelling, all-absorbing and never dies, and is the biggest thing in life, and the story of John Penn and Maria Cox will be whispered about in the backwoods cabins and wayside inns of the Pennsylvania Mountains long after seemingly greater men and minds have passed to forgetfulness. But for a few lines in the writings of Charles P. Keith, H. M. Jenkins, Nevin W. Moyer and various Penn biographers, such as Albert Cook Myers, the verbal memories of ’Squire W. H. Garman, James Till, Mrs. H. E. Wilvert and other old-time residents of the vicinity of “Tulliallan,” all would be lost, and the inspiration of a story of overwhelming affection unrecorded in the annals of those who love true lovers.
  • 58.
    II At His Bedside Whenold Jacob Loy passed away at the age of eighty years, he left a pot of gold to be divided equally among his eight children. It was a pot of such goodly proportions that there was a nice round sum for all, and the pity of it was after the long years of privation which had collected it, that some of the heirs wasted it quickly on organs, fast horses, cheap finery and stock speculations, for it was before the days of player-pianos, victrolas and automobiles. Yolande, his youngest daughter, was a really attractive girl, even had she not a share in the pot of gold, and had many suitors. Though farm raised and inured to hardships she was naturally refined, with wonderful dark eyes and hair, and pallid face–the perfect type of Pennsylvania Mountain loveliness. Above all her admirers she liked best of all Adam Drumheller, a shrewd young farmer of the neighborhood, and eventually married him. Three children were born in quick succession, in the small tenant house on his father’s farm in Chest Township, where the young couple had gone to live immediately after their wedding. Shortly after the birth of the last child old Jacob Drumheller died, and the son and his family moved into the big stone farmhouse near the banks of the sulphurous Clearfield Creek. It was not long after this fortuitous move that the young wife began to show signs of the favorite Pennsylvania mountain malady–consumption. Whether it was caused by a deep-seated cold or came about from sleeping in rooms with windows nailed shut, no one could tell, but the beautiful young woman became paler and more wax-like, until she realized that a speedy end was inevitable. Many times she found comfort in
  • 59.
    her misfortune byhaving her husband promise that in the event of her death he would never remarry. “Never, never,” he promised. “I could never find your equal again.” He was sincere in some respects; it would be hard to find her counterpart, and she had made a will leaving him everything she possessed, and he imagined that the pot of gold transformed into a bank balance or Government bonds would be found somewhere among her effects. Before ill health had set in he had quizzed her many times, as openly as he dared, on the whereabouts of her share of the pot. “It is all safe,” she would say. “It will be forthcoming some time when you need it more than you do today,” and he was satisfied. As she grew paler and weaker Adam began to think more of Alvira Hamel, another comely girl whom he had loved when he railroaded out of Johnstown, at Kimmelton, and whom he planned to claim as his own should Yolande pass away.
  • 60.
    SCENE IN SNYDER-MIDDLESWARTH PARK Perhapshis thoughts dimly reflected on the dying wife’s sub- conscious mind, for she became more insistent every day that he promise never to remarry. “Think of our dear little children,” she kept saying, “sentenced to have a stepmother; I would come back and haunt you if you perpetrate such a cruelty to me and mine.” Adam had little faith in a hereafter, and less in ghosts, so he readily promised anything, vowing eternal celebacy cheerfully and profoundly.
  • 61.
    When Yolande didfinally fade away, she died reasonably happy, and at least died bravely. She never shed a tear, for it is against the code of the Pennsylvania Mountain people to do so–perhaps a survival of the Indian blood possessed by so many of them. Three days after the funeral Adam hied himself to Ebensburg to “settle up the estate,” but also to look up Alvira Hamel, who was now living there. She seemed glad to see him, and when he broached a possible union she acted as if pleased at everything except to go on to that lonely farm on the polluted Clearfield Creek. By promising to sell out when he could and move to Barnesboro or Spangler, a light came in her dark eyes, and though he did not visit the lawyer in charge of his late wife’s affairs, his day in town was successful in arranging for the new alliance with his sweetheart of other days. In due course of time it was discovered that the equivalent of Yolande’s share of the pot of gold left by old Jacob Loy was not to be found. “She may have kept it in coin and buried it in the orchard,” was some of the very consoling advice that the lawyer gave. At any rate it was not located by the time that Adam and Alvira were married, but the bridegroom was well to do and could afford to wait. After a short trip to Pittsburg and Wheeling the newly married couple took up housekeeping in the big brick farmstead above the creek. The first night that they were back from the honeymoon–it was just about midnight and Alvira was sleeping peacefully–Adam thought that he heard footsteps on the stairs. He could not be mistaken. Noiselessly the door opened, and the form of Yolande glided into the room; she was in her shroud, all white, and her face was whiter than the shroud, and her long hair never looked blacker. Along the whitewashed wall by the bedside was a long row of hooks on which hung the dead woman’s wardrobe. It had never been disturbed; Alvira was going to cut the things up and make new garments out of them in the Spring. Adam watched the apparition while she moved over to the clothing, counting them, and smoothed and caressed each skirt or waist, as if she regretted having had to abandon them for the steady raiment of the shroud.
  • 62.
    Then she cameover to the bed and sat on it close to Adam, eyeing him intently and silently. Just then Alvira got awake, but apparently could see nothing of the ghost, although the room was bright as day, bathed in the full moon’s light. Yolande seemed to remain for a space of about ten minutes, then passed through the alcove into the room where the children were sleeping and stood by their bedside. The next night she was back again, repeating the same performance, the next night, and the next, and still the next, each night remaining longer, until at last she stayed until daybreak. In the morning as the hired men were coming up the boardwalk which led to the kitchen door, they would meet Yolande, in her shroud coming from the house, and passing out of the back gate. On one occasion Alvira was pumping water on the porch, but made no move as she passed, being evidently like so many persons, spiritually blind. The hired men had known Yolande all their lives, and were surprised to see her spooking in daylight, but refrained from saying anything to the new wife. Every day for a week after that she appeared on the kitchen porch, or on the boardwalk, in the yard, on the road, and was seen by her former husband many times, and also her night prowling went on as of yore. The hired men began to complain; it might make them sick if a ghost was around too much; these spooks were supposed to exhale a poison much as copperhead snakes do, and also draw their “life” away, and they threatened to quit if she wasn’t “laid.” All of them had seen spooks before, on occasion, but a daily visitation of the same ghost was more than they cared about. Had it not been for the excitable hired men, Adam, whose nerves were like iron, could have stood Yolande’s ghost indefinitely. In fact, he thought it rather nice of her to come back and see him and the children “for old time’s sake.” But the farm hands must be conserved at any cost, even to the extent of laying Yolande’s unquiet spirit. The next night when she appeared, he made bold and spoke to her: “What do you want, Yolande,” he said softly, so as not to wake the soundly sleeping Alvira at his side. “Is there anything I can do for you, dear?”
  • 63.
    Yolande came veryclose beside him, and bending down whispered in his ear: “Adam,” said she, “how can you ask me why I am here? You surely know. Did you not, time and time again, promise never to marry again, if I died, for the sake of our darling children? Did you not make such a promise, and see how quickly you broke it! Where I am now I can hold no resentments, so I forgive you for all your transgressions, but I hope that Alvira will be good to our children. I have one request to make: After I left you, you were keen to find what I did with my share of daddy’s pot of gold. I had it buried in the orchard at my old home, under the Northern Spy, but after we moved here, one time when you went deer hunting to Centre County, I dug it up and brought it over here and buried it in the cellar of this house. It is here now. There are just one hundred and fifty-three twenty dollar gold pieces; that was my share. The children and the money were on my mind, not your broken promise and rash marriage, which you will repent, and which I tell you again I forgive you for. I want my children to have that money, every one of the one hundred and fifty-three twenty dollar gold pieces. I buried it a little to the east of the spring in the cellar, about two feet under ground, in a tin cartridge box; Dig it up tomorrow morning, and if you find the one hundred and fifty-three coins, and give every one to the children, I will never come again and upset your hired men. Why I have Myron Shook about half scared to death already, but if you don’t find every single coin I’ll have to come back until you do, or if you hold it back from the children, you will not be able to keep a hireling on this place, or any other place to which you move. Many live folks can’t see ghosts; your wife is one of these; she will never worry until the hired men quit, then she’ll up and have you make sale and move to town. Be square and give the children the money, and I’ll not trouble you again.” “Oh, Yolande,” answered Adam in gentle tones, “you are no trouble to me, not in the least. I love to have you visit me at night, and look at the children, but you are making the hired help terribly uneasy. That part you must quit.” “That’s enough of your drivel, Adam,” spoke Yolande, in a sterner tone of voice. “Talk less like a fool, and more like a man. Dig up that
  • 64.
    money in themorning, count it, and give it to the children and I’ll be glad never to see you again.” To be reproached by a ghost was too much for Adam, and he lapsed into silence, while Yolande slipped out of the room, over to the bedside of the sleeping children, where she lingered until daylight. Adam was soon asleep, but was up bright and early the next morning, starting to dress just as the ghost glided out of the door. By six o’clock he had exhumed Yolande’s share of the pot of gold which was buried exactly as her ghostly self had described. It was a hard wrench to hand the money over to the children, or rather to take it to Ebensburg and start savings accounts in their names. But he did it without a murmur. The cashier, a horse fancier, gave him a present of a new whip, of a special kind that he had made to order at Pittsburg, so he came home happy and contented. Night was upon him, and supper over, he retired early, dozing a bit before the “witching hour.” As the old Berks County tall clock in the entry struck twelve, he began to watch for Yolande’s accustomed entrance. But not a shadow appeared. The clock struck the quarter, the half, three quarters and one o’clock. No Yolande or anything like her came; she was true to her promise, as true as he had been false. It was an advantage to be a ghost in some ways. They were honorable creatures. Adam did not know whether to feel pleased or not. His vanity had been not a little appealed to by a dead wife visiting him nightly; now he was sure that it wasn’t for love of him or jealousy, she had been coming back, but to see that the children got the money that had been buried in the cellar. And at last she had spoken rather unkindly, so the great change called death had ended her love, and she wasn’t grieving over his second marriage at all. However, he fell to consoling himself that she had chided him for breaking his word and marrying again; she must have cared for him or she would not have said those things. Then the thought came to him that she wasn’t really peeved at anything concerning his marriage to Alvira except that the children had gotten a stepmother. He wondered if Alvira would continue to be kind to them. Just as he went to sleep he had
  • 65.
    forgotten both Yolandeand Alvira, chuckling over a pretty High School girl he had seen on the street at the ’burg, and whom he had winked at.
  • 66.
    III. The Prostrate Juniper Weguarranwas a young warrior of the Wyandots, who lived on the shores of Lake Michigan. In the early spring of 1754 he was appointed to the body-guard of old Mozzetuk, a leader of the tribe, on an embassy to Bethlehem, in Pennsylvania, to prevail on the holy men there, as many Indians termed the Moravians, to send a band of Missionaries to the Wyandot Country, with a view of Christianizing the tribe, and acting as advisors and emissaries between the Wyandots and allied nations with the French and other white men, who were constantly encroaching on the redmen’s territories. Weguarran the youngest and the handsomest of the escort, was very impressionable, and across Ohio and over the Alleghenies, he made friends with the Indian maidens of the various encampments passed en route. The reception at Bethlehem was cordial, but not much hope was held out for an immediate despatch of Missionaries as the Moravians were anxious to avoid being drawn into the warlike aspirations of the English and French, preferring to promote the faith in pacified regions, as very few of them were partisans, but if they had a leaning at all, it was toward the French. This was due to the fact that the French always understood the Indians better than the English, were more sympathetic colonizers, and while many French Missionaries carried forward the tenets of Rome, there was no religious intolerance, and Missionaries of every faith seemed to thrive under their leadership. While at Bethlehem and Nazareth, Weguarran was much favored by the Indian maids of those localities, but did not wholly lose his
  • 67.
    heart until oneafternoon at the cabin of an old Christian Pequot named Michaelmas. This old Indian, a native of Connecticut, lived in a log cabin on a small clearing near the Lehigh River, where he cultivated a garden of rare plants and trees, and raised tobacco. All his pastimes were unusual; he captured wild pigeons, which he trained to carry messages, believing that they would be more valuable in wartime than runners. He also practiced falconry, owning several hawks of race, goshawks, marsh hawks and duck hawks. The goshawks he used for grouse, wood-cocks and quails; the marsh hawks for rabbits, hares and ’coons; and the duck hawks for wild ducks and other water birds, which fairly swarmed on the Lehigh in those days. He was a religious old man, almost a recluse, strong in his prejudices, and was much enthused by the Wyandot embassy, giving his waning hopes a new burst of life for an Indian renaissance. He took a great fancy to the manly and handsome Weguarran, inviting him to his cabin, and it was there that the youthful warrior met the old man’s lovely daughter, Wulaha. She was an only child, eighteen years of age. Her mother belonged to the Original People and was also a Christian. Love progressed very rapidly between Weguarran and Wulaha, and as the time drew near for the embassy to depart, the young girl intimated to her lover that he must discuss the subject with old Michaelmas, and secure his approval and consent, after the manner of white Christians. The old Pequot was not averse to the union, which would add another strain of Indian blood to the family, but stated that a marriage could only take place on certain conditions. Weguarran, in his conversations with Michaelmas, had told him of his military affiliations with the French, which had filled the old man’s heart with joy for the hopes of a new order of things that it seemed to kindle. When he asked the hand of the fair Wulaha in marriage, Michaelmas “came back” with the following proposition: “Weguarran, I am getting old and feeble,” he said. “I may pass away any time, and I could not bear the thought of my squaw being left alone, which would be the case if you married Wulaha and took
  • 68.
    her to thedistant shores of Lake Michigan. However, there are greater things than my death and my squaw’s loneliness, the future of the red race, now crushed to earth by the Wunnux, as we call the white men, but some day to be triumphant. You have told me that within this very year the French and Indians are sure to engage the English in a mighty battle which will decide the future history of the Continent. You can marry Wulaha right after that battle, if you are victorious; otherwise you can do as the Missionaries tell us the Romans did–fall on your sword. You can never return here, as I do not want my daughter to marry and continue the race of a beaten people. I would far rather have her die single, and have our seed perish, for if this victory is not won, doomed is every redman on this Continent. The only wish of the English is to encompass our extermination. Wulaha will remain at home until after that battle, when you can come for her and claim her as your own, and we will give her to you with rejoicing.” “What you say is surely fair enough, Father Michaelmas,” replied Weguarran, “for I would see no future for Wulaha and myself if the English are victorious in this inevitable battle. As soon as it is won– and it will be won, for the high resolve of every Indian warrior is to go in to win–I will hurry back to the banks of the Lehigh, never stopping to rest, sleep or eat, to tell you of the glad tidings, and bear away my beloved Wulaha. I want to ask one special favor of you. I have admired your wonderful cage of trained wild pigeons, which you say will carry messages hundreds of miles. Lend me one of these pigeons, and as soon as the victory is won, I will release the bird, and while I am speeding eastward on foot, our feathered friend will fly on ahead and end the suspense, and bring joy to yourself, your squaw and Wulaha.” “I will gladly let you have my best trained pigeon, or hawk, or anything I possess, if I can learn of the victory, but in turn I will ask a favor of you. I listened with breathless interest to your tales of the Prostrate Junipers which grow on the shores of the great lakes, which cover two thousand square feet, and are hundreds of years old. You promised to bring me a scion of one of those curious trees, so that I might plant it in my garden of rare trees and shrubs. Now,
  • 69.
    here will bea chance to associate it with the great victory; pluck a stout but small scion, and if the victory is won, affix it firmly to one of the pigeon’s legs and let it go. If it comes back without the twig of Juniper I will know that our cause has lost, and while you fall on your sword, I and my family will jump into the Lehigh.” “I will gladly do as you say, Father Michaelmas,” said Weguarran, “and will send a twig that will grow, and some day make a noble tree, and in years to come, our people will call it Weguarran’s Victory Tree. The fact that it is a Prostrate Tree makes it all the more appropriate, as it will represent the English race lying prostrated, crushed by the red race they wronged, and by our kindly and just French allies.” Weguarran was so inspired by the thought of the pigeon messenger, the sprig of Prostrate Juniper, and the impending victory that it assuaged his grief at the parting from Wulaha, sending him away determined to give a good account of himself in all things. Old Michaelmas selected a handsome cock pigeon, with a dragon’s blood red breast–his very best and most intelligent, and surest flyer, named Wuskawhan, which he placed in a specially built, bottle shaped basket, which had no lid, yet the top was too small for the bird to escape. In this way it could rise up and peer out, as it was carried along, and not bruise its wing coverts or head, as it would if it flew against the top of a square basket with a lid. After a touching parting with Wulaha, her mother and father, the young warrior went his way with his precious burden. The Indians, even old Mozzetuk, were rapid travellers, and in due time they reached the country of the Prostrate Junipers on the shores of Lake Michigan. They arrived in what seemed like an armed camp, for all the braves had been called to arms, which plotted to drive Indians and French to the uttermost ends of the earth. Weguarran was quickly mobilized, and a musket in one hand and tomahawk in the other, while on his back he bore the sacred pigeon, he marched toward his foes. In the excitement he had not forgotten to slip into his pouch at his belt a sprig of the Prostrate Juniper, which would be the emblem of the English race prostrate under the foot of French and Indian allies.
  • 70.
    In due courseof time the army of which the picked Wyandot warriors formed a part, met their English foemen on Braddock’s Field, completely routing and all but annihilating them. General Braddock himself was shot from behind by one of his own men in the wild stampede, and the French and Indians were completely victorious. Surveying the gorey scene, every wooded glade lying thick with dead redcoats and broken accoutrements, Weguarran carefully opened the panther skin pouch at his best, taking out the sprig of Prostrate Juniper. Then he lifted the handsome wild pigeon from its bottle-nosed cage of oak withes, and with a light leathern string, affixed the little twig, on which the berries still clustered, to the bird’s leg, then tossed the feathered messenger up into the air. The pigeon quickly rose above the trees, circled a few times, and then started rapidly for the east, as fast as his broad, strong wings could carry him. This done, Weguarran visited his chief, obtaining leave to proceed to Bethlehem to claim his bride, promising to report back with her on the banks of the Ohio as speedily as possible. The pigeon naturally had a good start, and by the next morning was flying over the palisaded walls of John Harris’ Trading Post on the Susquehanna. A love story was being enacted within those walls, in the shadow of one of the huge sheds used in winter to store hides. Keturah Lindsay, Harris’ niece, an attractive, curly-haired Scotch girl, was talking with a young Missionary whom she admired very much, Reverend Charles Pyrleus, the protege of Col. Conrad Weiser. Unfortunately they had to meet by stealth as his attentions were not favored by the girl’s relatives, who considered him of inferior antecedents. They had met in the shed this fair July morning, whether by design or accident, no one can tell, and were enjoying one another’s society to the utmost. In the midst of their mutual adoration, the dinner gong was sounded at the trading house, and Keturah, fearful of a scolding, reluctantly broke away. As she came out into the sunlight, she noticed a handsome wild pigeon drop down, as if exhausted, on one
  • 71.
    of the topmoststakes of the palisade which surrounded the trading house and sheds. Keturah, like many frontier girls, always carried a gun, and quickly taking aim, fired, making the feathers fly, knocking the bird off its perch, and it seemed to fall to the ground outside the stockade. In a minute it rose, and started to fly off towards the east. She had reloaded, so fired a second time, but missed. “How strange to see a wild pigeon travelling through here at this time of year,” she thought, as carrying her smoking firearm, she hurried to the mess room of the big log trading house. The messenger pigeon had been grievously hurt, but was determined to go “home.” On and on it went, sometimes “dipping” like a swallow, from loss of blood, but by sheer will power keeping on the wing. As it neared the foothills of the South Mountains, near the village of Hockersville, with old Derry Church down in the vale, it faltered, spun about like a pin wheel, and fell with a thud. Gulping and blinking a few times, it spread out its wide pinions and lay on its breastbone–stone dead–the twig of Prostrate Juniper still affixed to one of its carmine feet. There it lay, brave in death, until the storms and winds shivered it, and it rotted into the ground. Weguarran was a rapid traveler, and in forced marches came to the shady banks of the Lehigh in three or four days. He was so excited that he swam the stream. He brought the first news of the great victory in the west to the surprised Michaelmas and his friends. But where was the prized wild pigeon, Wuskawhan? It could not have gone astray, for such a bird’s instinct never erred. “Caught by a hawk or shot down by some greedy fool of a Wunnux” was the way in which old Michaelmas explained its non-appearance. The news spread to the white settlements and to the towns, and there was consternation among all sympathizers with the Crown– with all except a few Moravians who were mum for policy’s sake, and the Indians, whose stoical natures alone kept them from disclosing the elation that was in their hearts.
  • 72.
    A MAMMOTH SHORT-LEAFPINE “The English never wanted the Indians civilized,” said Michaelmas, boldly. “They drove the Moravians out of Schadikoke and from the Housatonic when they saw the progress they made with our people; were it not for the Quakers in Pennsylvania, they would have had no place to harbor; those of us who felt the need of these kind friends followed them in their exile, but we can never forgive that we had to leave the Connecticut country of our birth under such circumstances. I am glad that our enemies were beaten and annihilated.” Weguarran was baptized, and he and the lovely Wulaha were married by one of the Moravian preachers, and started for the great lake country, which was to be their permanent home.
  • 73.
    Michaelmas and hissquaw were too old to make the long journey, but they were happy in their garden of rare trees and plants, the wild pigeons, the hawks of race, and the dreams of an Indian renaissance. They lived many years afterwards, and are buried with the other Christian Indians at Bethlehem. Out in the foothills of the South Mountains, overlooking old Derry Church, in the fertile Lebanon Valley among the pines and oaks and tulip trees, a strange seedling appeared in the spring of 1756, different from anything that the mountain had known since prehistoric times. Instead of growing upward and onward as most brave trees do, it spread out wider and greater and vaster, until, not like the symbol of the Anglo-Saxon prone beneath the heel of French and Indian, it was the symbol of the all diffusing power of the English speaking race, which has grafted its ideals and hopes and practical purposes over the entire American Continent. Nourished by the life’s blood of the travelling pigeon that bore it there, it had a flying start in the battle of existence, and today, after all these years, bids fair to last many years longer, to be the arboral marvel and wonder of the Keystone State. Well may the Boy Scouts of Elizabethtown feel proud to be the honorary custodians of this unique tree with its spread of 2,000 feet, for apart from its curious appearance and charm, it has within it memories of history and romance, of white men and red, that make it a veritable treasure trove for the historian and the folk-lorist, and all those who love the great outdoors in this wonderful Pennsylvania of ours!
  • 74.
    IV. Out of theAshes Last Autumn we were crossing Rea’s Hill one afternoon of alternate sunshine and shadow, and as we neared the summit, glanced through several openings in the trees at the wide expanse of Fulton County valleys and coves behind us, on to the interminable range upon range of dark mountains northward. In the valleys here and there were dotted square stone houses, built of reddish sandstone, with high roofs and chimneys, giving a foreign or Scottish air to the scene. Some of these isolated structures were deserted, with windows gaping and roofs gone, pictures of desolation and bygone days. Just as the crest of the mountain was gained, we came upon a stone house in process of demolition, in fact all had been torn away, and the sandstone blocks piled neatly by the highway, all but the huge stone chimney and a small part of one of the foundation walls. Work of the shorers had temporarily ceased for it was a Saturday afternoon. Affixed to the chimney was a wooden mantel, painted black, of plain, but antique design, exposed, and already stained by the elements, and evidently to be abandoned by those in charge of the demolition. The house stood on the top of a steep declivity, giving a marvelous view on four sides, almost strategic enough to have been a miniature fortress! It was the first time in a dozen years that we had passed the site; in 1907 the house was standing and tenanted, and pointed out as having been a temporary resting place of General John Forbes on his eastern march, after the successful conquest of Fort Duquesne, in
  • 75.
    1758. Now allis changed, historic memories had not kept the old house inviolate; it was to be ruthlessly destroyed, perhaps, like the McClure Log College near Harrisburg, to furnish the foundations for a piggery, or some other ignoble purpose. As we passed, a pang of sorrow overcame us at the lowly state to which house and fireplace had fallen, and we fell to recounting some of the incidents of the historic highway, in military and civil history, the most noteworthy road in the Commonwealth. The further, on we traveled, the more we regretted not stopping and trying to salvage the old wooden mantel, but one of our good friends suggested that if we did not are to return for it, we should mention the matter to the excellent and efficient Leslie Seylar at McConnellsburg, who knew everyone and everything, and could doubtless obtain the historic relic and have it shipped to our amateur “curio shop.” The genial Seylar, famed for his temperamental and physical resemblance to the lamented “Great Heart,” was found at his eyrie and amusement centre on top of Cove Mountain, and he gladly consented to securing the abandoned mantel. As a result it is now in safe hands, a priceless memento of the golden age of Pennsylvania History. But now for the story or the legend of the mantel, alluded to briefly last year in the chapter called the “Star of the Glen,” in this writer’s “South Mountain Sketches.” The story, as an old occupant of the house told it, and he survived on until early in the Nineteenth Century was, that General Forbes, on this victorious eastern march, was seized many times with fainting fits. On every occasion his officers and orderlies believed that the end had come, so closely did he simulate death. But he had always been delicate, at least from his first appearance in Pennsylvania, though when campaigning with the gallant Marshal Ligonier in France, Flanders and on the Rhine, participating in the battles of Dettingen, Fontenoy and Lauffeld, no such symptoms were noted. Although less than fifty years of age when he started towards the west, he was regarded, from his illnesses, as an aged person, Sherman Day in his inimitable “Historical Collections” states that there was “much dissatisfaction in
  • 76.
    the choice ofa leader of the expedition against Fort Duquesne, as General Forbes, the commander, was a decrepit old man.” What caused his ill health history has not uncovered at this late date. It has been said that he was an epileptic, like Alexander and other great generals, or a sufferer from heart trouble or general debility. His military genius outweighed his physical frailties, so that he rose superior to him, but it must not be forgotten that he was aided by two brilliant officers, Colonel George Washington and Colonel Henry Bouquet. His immediate entourage was a remarkable one, even for a soldier of many wars. Like a true Scotsman, he carried his own piper with him, Donald MacKelvie, said to be a descendant of the mighty MacCrimmons; and his bodyguard was also headed by a Highlander, Andrew MacCochran, who had been a deer stalker on one of the estates owned by the General’s father. Forbes himself, being a younger son, was not a man of property, and Pittencrief House, his birth-place, was already occupied by an older brother, from whom, so Dr. Burd S. Patterson tells us, all who claim relationship to him are descended. The General was carried in a hammock, with frequent stops, from Harris’ Ferry to Fort Duquesne, and back again, borne by four stalwart Highlanders, in their picturesque native costumes, wearing the tartan of the Forbes clan. The deerstalker, MacCochran, was the major domo, and even above the chief of staff and Brigade Surgeon, gave the orders to halt when the General’s lean weazened face indicated an over-plussage of fatigue. It was late in the afternoon as the returning army had neared the summit of Rea’s Hill; the pipers were playing gaily Blaz Sron, to cheer foot soldiers and wagoners up the steep, rocky, uneven grade, with the General in the van. The ascent was a hard one, and the ailing commander-in-chief was shaken about considerably, so much so that MacCochran was glad to note the little stone house, where he might give him his much needed rest. Old Andrew McCreath and his wife, a North of Ireland couple, the former a noted hunter, occupied the house; their son was serving in the Pennsylvania Regiment, which formed a part of General Forbes’
  • 77.
    Welcome to ourwebsite – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebooknice.com