Programming TypeScript Making your JavaScript applications scale Boris Cherny install download https://ebookmeta.com/product/programming-typescript-making-your- javascript-applications-scale-boris-cherny/ Download more ebook from https://ebookmeta.com
Boris Cherny Programming TypeScript Making Your JavaScript Applications Scale
Praise for Programming TypeScript This is the right book to help you learn TypeScript in depth. Programming TypeScript shows all the benefits of using a type system on top of JavaScript and provides deep insight into how to master the language. —Minko Gechev, Engineer, Angular Team at Google Programming TypeScript onboarded me to the TypeScript tooling and overall ecosystem quickly and efficiently. Every usage question I had was covered by concise, real-world examples. The “Advanced Types” chapter breaks down terminology I usually stumble over, and shows how to leverage TypeScript to create extremely safe code that’s still pleasant to use. —Sean Grove, Cofounder of OneGraph Boris has provided a comprehensive guide to TypeScript. Read this for the 10,000-foot view all the way back down to Earth, and then some. —Blake Embrey, Engineer at Opendoor, author of TypeScript Node and Typings
Boris Cherny Programming TypeScript Making Your JavaScript Applications Scale Boston Farnham Sebastopol Tokyo Beijing Boston Farnham Sebastopol Tokyo Beijing
978-1-492-03765-1 [LSI] 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/institu‐ tional sales department: 800-998-9938 or corporate@oreilly.com. Development Editor: Angela Rufino Indexer: Ellen 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 2019-08-09: Second 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.
To Sasha and Michael, who might also fall in love with types, someday.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2. TypeScript: A 10_000 Foot View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 The Compiler 5 The Type System 7 TypeScript Versus JavaScript 8 Code Editor Setup 11 tsconfig.json 11 tslint.json 13 index.ts 13 Exercises 15 3. All About Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Talking About Types 18 The ABCs of Types 19 any 19 unknown 20 boolean 21 number 22 bigint 23 string 23 symbol 24 Objects 25 Intermission: Type Aliases, Unions, and Intersections 30 Arrays 33 vii
Tuples 35 null, undefined, void, and never 37 Enums 39 Summary 43 Exercises 44 4. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Declaring and Invoking Functions 45 Optional and Default Parameters 47 Rest Parameters 48 call, apply, and bind 50 Typing this 50 Generator Functions 52 Iterators 53 Call Signatures 55 Contextual Typing 58 Overloaded Function Types 58 Polymorphism 64 When Are Generics Bound? 68 Where Can You Declare Generics? 69 Generic Type Inference 71 Generic Type Aliases 73 Bounded Polymorphism 74 Generic Type Defaults 78 Type-Driven Development 79 Summary 80 Exercises 81 5. Classes and Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Classes and Inheritance 83 super 89 Using this as a Return Type 89 Interfaces 91 Declaration Merging 93 Implementations 94 Implementing Interfaces Versus Extending Abstract Classes 96 Classes Are Structurally Typed 97 Classes Declare Both Values and Types 98 Polymorphism 100 Mixins 101 Decorators 104 viii | Table of Contents
Simulating final Classes 107 Design Patterns 107 Factory Pattern 108 Builder Pattern 109 Summary 110 Exercises 110 6. Advanced Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Relationships Between Types 114 Subtypes and Supertypes 114 Variance 115 Assignability 121 Type Widening 122 Refinement 126 Totality 130 Advanced Object Types 132 Type Operators for Object Types 132 The Record Type 137 Mapped Types 137 Companion Object Pattern 140 Advanced Function Types 141 Improving Type Inference for Tuples 141 User-Defined Type Guards 142 Conditional Types 143 Distributive Conditionals 144 The infer Keyword 145 Built-in Conditional Types 146 Escape Hatches 147 Type Assertions 148 Nonnull Assertions 149 Definite Assignment Assertions 151 Simulating Nominal Types 152 Safely Extending the Prototype 154 Summary 156 Exercises 157 7. Handling Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Returning null 160 Throwing Exceptions 161 Returning Exceptions 163 The Option Type 165 Table of Contents | ix
Summary 171 Exercises 172 8. Asynchronous Programming, Concurrency, and Parallelism. . . . . . . . . . . . . . . . . . . . . . 173 JavaScript’s Event Loop 174 Working with Callbacks 176 Regaining Sanity with Promises 178 async and await 183 Async Streams 184 Event Emitters 184 Typesafe Multithreading 187 In the Browser: With Web Workers 187 In NodeJS: With Child Processes 196 Summary 197 Exercises 198 9. Frontend and Backend Frameworks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Frontend Frameworks 199 React 201 Angular 207 Typesafe APIs 210 Backend Frameworks 212 Summary 213 10. Namespaces.Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 A Brief History of JavaScript Modules 216 import, export 218 Dynamic Imports 219 Using CommonJS and AMD Code 221 Module Mode Versus Script Mode 222 Namespaces 222 Collisions 225 Compiled Output 225 Declaration Merging 226 Summary 228 Exercise 228 11. Interoperating with JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Type Declarations 230 Ambient Variable Declarations 233 Ambient Type Declarations 234 x | Table of Contents
Ambient Module Declarations 235 Gradually Migrating from JavaScript to TypeScript 236 Step 1: Add TSC 237 Step 2a: Enable Typechecking for JavaScript (Optional) 238 Step 2b: Add JSDoc Annotations (Optional) 239 Step 3: Rename Your Files to .ts 240 Step 4: Make It strict 241 Type Lookup for JavaScript 242 Using Third-Party JavaScript 244 JavaScript That Comes with Type Declarations 245 JavaScript That Has Type Declarations on DefinitelyTyped 245 JavaScript That Doesn’t Have Type Declarations on DefinitelyTyped 246 Summary 247 12. Building and Running TypeScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Building Your TypeScript Project 249 Project Layout 249 Artifacts 250 Dialing In Your Compile Target 251 Enabling Source Maps 255 Project References 255 Error Monitoring 258 Running TypeScript on the Server 258 Running TypeScript in the Browser 259 Publishing Your TypeScript Code to NPM 261 Triple-Slash Directives 262 The types Directive 262 The amd-module Directive 264 Summary 265 13. Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 A. Type Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 B. Type Utilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 C. Scoped Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 D. Recipes for Writing Declaration Files for Third-Party JavaScript Modules. . . . . . . . . . . 275 E. Triple-Slash Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Table of Contents | xi
F. TSC Compiler Flags for Safety. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 G. TSX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 xii | Table of Contents
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, docu‐ ment 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 intu‐ itive, 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 con‐ cisely and precisely, letting you write applications in a way that’s fun, modern, and safe. Preface | xiii
How This Book Is Organized This book has two aims: to give you a deep understanding of how the TypeScript lan‐ guage 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 top‐ ics 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 ver‐ sion is usually just called “esnext”). This will keep your code in line with the lat‐ est 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. xiv | Preface
1 If you’re not coming from JavaScript, here’s an example: if you have an object o, and you want to add a prop‐ erty 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}. • You should keep your data structures immutable with spreads (...) most of the time.1 • You should make sure everything has a type, inferred when possible. Be careful not to abuse explicit types; 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 “Polymor‐ phism” on page 64) 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 func‐ tions. 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 leg‐ acy 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 ele‐ ments such as variable or function names, data types, environment variables, statements, and keywords. Preface | xv
Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. 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 signifi‐ cant 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. xvi | Preface
O’Reilly Online Learning For almost 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help compa‐ nies 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 bookques‐ tions@oreilly.com. For more information about our books, courses, conferences, and news, see our web‐ site 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 Preface | xvii
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’Reilly 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” on page 210, and to Shyam Seshadri for his contri‐ bution in “Angular” on page 207. 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. xviii | Preface
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. 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 Inter‐ net of Things (IoT) devices. It will make your programs safer by checking for com‐ mon 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.1 1
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 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 obvi‐ ously 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 add a number and an array? let obj = {} obj.foo // Error: You forgot to define the property "foo" on obj. function a(b) { return b/2 } a("z") // Error: The function "a" expects a number, // but you gave it a string. Don’t get me wrong: trying to fix our mistakes for us is a neat feature for a program‐ ming language to have (if only it worked for more than just programs!). But for Java‐ Script, 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? 2 | Chapter 1: Introduction
2 If you’re not sure what “type level” means here, don’t worry. We’ll go over it in depth in later chapters. 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 '+' cannot be applied to types '3' // and 'never[]'. let obj = {} obj.foo // Error TS2339: Property 'foo' does not exist on type '{}'. function a(b: number) { return b / 2 } a("z") // Error TS2345: Argument of type '"z"' is not assignable to // 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;2 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! Introduction | 3
CHAPTER 2 TypeScript: A 10_000 Foot View Over the next few chapters, I’ll introduce the TypeScript language, give you an over‐ view of how the TypeScript Compiler (TSC) works, and take you on a tour of Type‐ Script’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 trans‐ forms 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. 5
3. Bytecode is evaluated by the runtime. Where TypeScript is special is that instead of compiling straight to bytecode, Type‐ Script compiles to… JavaScript code! You then run that JavaScript code like you nor‐ mally 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. JavaScript compilers and runtimes tend to be smushed into a single program called an engine; as a programmer, this is what you’ll nor‐ mally 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. 6 | Chapter 2: TypeScript: A 10_000 Foot View
1 There are languages all over this spectrum: JavaScript, Python, and Ruby infer types at runtime; Haskell and OCaml infer and check missing types at compile time; Scala and TypeScript require some explicit types and infer and check the rest at compile time; and Java and C need explicit annotations for almost everything, which they check at compile time. In this process, steps 1–2 use your program’s types; step 3 does not. That’s worth reit‐ erating: 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 gener‐ ated 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 break‐ ing 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.1 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 booleans 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 let c = [true, false] // c is an array of booleans 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 The Type System | 7
annotations only when necessary, and let TypeScript work its inference magic for us whenever possible. 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 Java‐ Script’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 pro‐ gram 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 Java‐ Script to typed TypeScript (more on that in “Gradually Migrating from JavaScript to TypeScript” on page 236), 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 8 | Chapter 2: TypeScript: A 10_000 Foot View
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, Type‐ Script complains as soon as you do something invalid. When you run that same Java‐ Script code through TSC, you’ll get an error: 3 + [1]; // Error TS2365: Operator '+' cannot be applied to // types '3' and 'number[]'. (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 The Type System | 9
2 To be sure, JavaScript surfaces syntax errors and a few select bugs (like multiple const declarations with the same name in the same scope) after it parses your program, but before it runs it. If you parse your JavaScript as part of your build process (e.g., with Babel), you can surface these errors at build time. 3 Incrementally compiled languages can be quickly recompiled when you make a small change, rather than having to recompile your whole program (including the parts you didn’t touch). 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.2 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 an amazing experience if you’ve never worked with an incrementally compiled statically typed language before.3 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. 10 | Chapter 2: TypeScript: A 10_000 Foot View
4 This puts TSC in the mystical class of compilers known as self-hosting compilers, or compilers that compile themselves. 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 Sub‐ lime 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,4 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. 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 NodeJS 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. Code Editor Setup | 11
5 For this exercise, we’re creating a tsconfig.json manually. When you set up TypeScript projects in the future, you can use TSC’s built-in initialize command to generate one for you: ./node_modules/.bin/tsc --init. Create a new file called tsconfig.json in your root folder (touch tsconfig.json),5 then pop it open in your code editor and give it the following contents: { "compilerOptions": { "lib": ["es2015"], "module": "commonjs", "outDir": "dist", "sourceMap": true, "strict": true, "target": "es2015" }, "include": [ "src" ] } Let’s briefly go over some of those options and what they mean (Table 2-2): Table 2-2. tsconfig.json options Option Description include Which folders should TSC look in to find your TypeScript files? lib Which APIs should TSC assume exist in the environment you’ll be running your code in? This includes things like ES5’s Function.prototype.bind, ES2015’s Object.assign, and the DOM’s document.querySelector. module Which module system should TSC compile your code to (CommonJS, SystemJS, ES2015, etc.)? outDir Which folder should TSC put your generated JavaScript code in? strict Be as strict as possible when checking for invalid code. This option enforces that all of your code is properly typed. We’ll be using it for all of the examples in the book, and you should use it for your TypeScript project too. target Which JavaScript version should TSC compile your code to (ES3, ES5, ES2015, ES2016, etc.)? These are just a few of the available options—tsconfig.json supports dozens of options, and new ones are added all the time. You won’t find yourself changing these much in practice, besides dialing in the module and target settings when switching to a new module bundler, adding "dom" to lib when writing TypeScript for the browser (you’ll learn more about this in Chapter 12), or adjusting your level of strictness when migrating your existing JavaScript code to TypeScript (see “Gradu‐ ally Migrating from JavaScript to TypeScript” on page 236). For a complete and up-to- date list of supported options, head over to the official documentation on the TypeScript website. 12 | Chapter 2: TypeScript: A 10_000 Foot View
Note that while using a tsconfig.json file to configure TSC is handy because it lets us check that configuration into source control, you can set most of TSC’s options from the command line too. Run ./node_modules/.bin/tsc --help for a list of available command-line options. tslint.json Your project should also have a tslint.json file containing your TSLint configuration, codifying whatever stylistic conventions you want for your code (tabs versus spaces, etc.). Using TSLint is optional, but it’s strongly recommend for all Type‐ Script projects to enforce a consistent coding style. Most impor‐ tantly, it will save you from arguing over code style with coworkers during code reviews. The following command will generate a tslint.json file with a default TSLint configuration: ./node_modules/.bin/tslint --init You can then add overrides to this to conform with your own coding style. For exam‐ ple, my tslint.json looks like this: { "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "rules": { "semicolon": false, "trailing-comma": false } } For the full list of available rules, head over to the TSLint documentation. You can also add custom rules, or install extra presets (like for ReactJS). index.ts Now that you’ve set up your tsconfig.json and tslint.json, create a src folder containing your first TypeScript file: mkdir src touch src/index.ts index.ts | 13
Your project’s folder structure should now look this: chapter-2/ ├──node_modules/ ├──src/ │ └──index.ts ├──package.json ├──tsconfig.json └──tslint.json Pop open src/index.ts in your code editor, and enter the following TypeScript code: console.log('Hello TypeScript!') Then, compile and run your TypeScript code: # Compile your TypeScript with TSC ./node_modules/.bin/tsc # Run your code with NodeJS node ./dist/index.js If you’ve followed all the steps here, your code should run and you should see a single log in your console: Hello TypeScript! That’s it—you just set up and ran your first TypeScript project from scratch. Nice work! Since this might have been your first time setting up a TypeScript project from scratch, I wanted to walk through each step so you have a sense for all the moving pieces. There are a couple of short‐ cuts you can take to do this faster next time: • Install ts-node, and use it to compile and run your TypeScript with a single command. • Use a scaffolding tool like typescript-node-starter to quickly generate your folder structure for you. 14 | Chapter 2: TypeScript: A 10_000 Foot View
Exercises Now that your environment is set up, open up src/index.ts in your code editor. Enter the following code: let a = 1 + 2 let b = a + 3 let c = { apple: a, banana: b } let d = c.apple * 4 Now hover over a, b, c, and d, and notice how TypeScript infers the types of all your variables for you: a is a number, b is a number, c is an object with a specific shape, and d is also a number (Figure 2-3). Figure 2-3. TypeScript inferring types for you Play around with your code a bit. See if you can: • Get TypeScript to show a red squiggly when you do something invalid (we call this “throwing a TypeError“). • Read the TypeError, and try to understand what it means. • Fix the TypeError and see the red squiggly disappear. If you’re ambitious, try to write a piece of code that TypeScript is unable to infer the type for. Exercises | 15
CHAPTER 3 All About Types In the last chapter I introduced the idea of type systems, but I never defined what the type in type system really means. Type A set of values and the things you can do with them. If that sounds confusing, let me give a few familiar examples: • The boolean type is the set of all booleans (there are just two: true and false) and the operations you can perform on them (like ||, &&, and !). • The number type is the set of all numbers and the operations you can perform on them (like +, -, *, /, %, ||, &&, and ?), including the methods you can call on them like .toFixed, .toPrecision, .toString, and so on. • The string type is the set of all strings and the operations you can perform on them (like +, ||, and &&), including the methods you can call on them like .concat and .toUpperCase. When you see that something is of type T, not only do you know that it’s a T, but you also know exactly what you can do with that T (and what you can’t). Remember, the whole point is to use the typechecker to stop you from doing invalid things. And the way the typechecker knows what’s valid and what’s not is by looking at the types you’re using and how you’re using them. In this chapter we’ll take a tour of the types available in TypeScript and cover the basics of what you can do with each of them. Figure 3-1 gives an overview. 17
Figure 3-1. TypeScript’s type hierarchy Talking About Types When programmers talk about types, they share a precise, common vocabulary to describe what they mean. We’re going to use this vocabulary throughout this book. Say you have a function that takes some value and returns that value multiplied by itself: function squareOf(n) { return n * n } squareOf(2) // evaluates to 4 squareOf('z') // evaluates to NaN Clearly, this function will only work for numbers—if you pass anything besides a number to squareOf, the result will be invalid. So what we do is explicitly annotate the parameter’s type: function squareOf(n: number) { return n * n } squareOf(2) // evaluates to 4 squareOf('z') // Error TS2345: Argument of type '"z"' is not assignable to // parameter of type 'number'. Now if we call squareOf with anything but a number, TypeScript will know to com‐ plain right away. This is a trivial example (we’ll talk a lot more about functions in the next chapter), but it’s enough to introduce a couple of concepts that are key to talking 18 | Chapter 3: All About Types
about types in TypeScript. We can say the following things about the last code exam‐ ple: 1. squareOf’s parameter n is constrained to number. 2. The type of the value 2 is assignable to (equivalently: compatible with) number. Without a type annotation, squareOf is unconstrained in its parameter, and you can pass any type of argument to it. Once we constrain it, TypeScript goes to work for us verifying that every place we call our function, we call it with a compatible argument. In this example the type of 2 is number, which is assignable to squareOf’s annotation number, so TypeScript accepts our code; but 'z' is a string, which is not assignable to number, so TypeScript complains. You can also think of it in terms of bounds: we told TypeScript that n’s upper bound is number, so any value we pass to squareOf has to be at most a number. If it’s anything more than a number (like, if it’s a value that might be a number or might be a string), then it’s not assignable to n. I’ll define assignability, bounds, and constraints more formally in Chapter 6. For now, all you need to know is this is the language that we use to talk about whether or not a type can be used in a place where we require a certain type. The ABCs of Types Let’s take a tour of the types TypeScript supports, what values they contain, and what you can do with them. We’ll also cover a few basic language features for working with types: type aliases, union types, and intersection types. any any is the Godfather of types. It does anything for a price, but you don’t want to ask any for a favor unless you’re completely out of options. In TypeScript everything needs to have a type at compile time, and any is the default type when you (the pro‐ grammer) and TypeScript (the typechecker) can’t figure out what type something is. It’s a last resort type, and you should avoid it when possible. Why should you avoid it? Remember what a type is? (It’s a set of values and the things you can do with them.) any is the set of all values, and you can do anything with any. That means that if you have a value of type any you can add to it, multiply by it, call .pizza() on it—anything. any makes your value behave like it would in regular JavaScript, and totally prevents the typechecker from working its magic. When you allow any into your code you’re flying blind. Avoid any like fire, and use it only as a very, very last resort. The ABCs of Types | 19
On the rare occasion that you do need to use it, you do it like this: let a: any = 666 // any let b: any = ['danger'] // any let c = a + b // any Notice how the third type should report an error (why are you trying to add a num‐ ber and an array?), but doesn’t because you told TypeScript that you’re adding two anys. If you want to use any, you have to be explicit about it. When TypeScript infers that some value is of type any (for example, if you forgot to annotate a function’s parameter, or if you imported an untyped JavaScript module), it will throw a compile-time exception and toss a red squiggly at you in your editor. By explicitly annotating a and b with the any type (: any), you avoid the exception—it’s your way of telling TypeScript that you know what you’re doing. TSC Flag: noImplicitAny By default, TypeScript is permissive, and won’t complain about values that it infers as any. To get TypeScript to complain about implicit anys, be sure to enable the noImplicitAny flag in your tsconfig.json. noImplicitAny is part of the strict family of TSC flags, so if you already enabled strict in your tsconfig.json (as we did in “tscon‐ fig.json” on page 11), you’re good to go. unknown If any is the Godfather, then unknown is Keanu Reeves as undercover FBI agent Johnny Utah in Point Break: laid back, fits right in with the bad guys, but deep down has a respect for the law and is on the side of the good guys. For the few cases where you have a value whose type you really don’t know ahead of time, don’t use any, and instead reach for unknown. Like any, it represents any value, but TypeScript won’t let you use an unknown type until you refine it by checking what it is (see “Refinement” on page 126). What operations does unknown support? You can compare unknown values (with ==, ===, ||, &&, and ?), negate them (with !), and refine them (like you can any other type) with JavaScript’s typeof and instanceof operators. Use unknown like this: let a: unknown = 30 // unknown let b = a === 123 // boolean let c = a + 10 // Error TS2571: Object is of type 'unknown'. if (typeof a === 'number') { let d = a + 10 // number } 20 | Chapter 3: All About Types
1 Almost. When unknown is part of a union type, the result of the union will be unknown. You’ll read more about union types in “Union and intersection types” on page 32. This example should give you a rough idea of how to use unknown: 1. TypeScript will never infer something as unknown—you have to explicitly anno‐ tate it (a).1 2. You can compare values to values that are of type unknown (b). 3. But, you can’t do things that assume an unknown value is of a specific type (c); you have to prove to TypeScript that the value really is of that type first (d). boolean The boolean type has two values: true and false. You can compare them (with ==, ===, ||, &&, and ?), negate them (with !), and not much else. Use boolean like this: let a = true // boolean var b = false // boolean const c = true // true let d: boolean = true // boolean let e: true = true // true let f: true = false // Error TS2322: Type 'false' is not assignable // to type 'true'. This example shows a few ways to tell TypeScript that something is a boolean: 1. You can let TypeScript infer that your value is a boolean (a and b). 2. You can let TypeScript infer that your value is a specific boolean (c). 3. You can tell TypeScript explicitly that your value is a boolean (d). 4. You can tell TypeScript explicitly that your value is a specific boolean (e and f). In general, you will use the first or second way in your programs. Very rarely, you’ll use the fourth way—only when it buys you extra type safety (I’ll show you examples of that throughout this book). You will almost never use the third way. The second and fourth cases are particularly interesting because while they do some‐ thing intuitive, they’re supported by surprisingly few programming languages and so might be new to you. What I did in that example was say, “Hey TypeScript! See this variable e here? e isn’t just any old boolean—it’s the specific boolean true.” By using a value as a type, I essentially limited the possible values for e and f from all booleans to one specific boolean each. This feature is called type literals. The ABCs of Types | 21
2 At the time of writing, you can’t use NaN, Infinity, or -Infinity as type literals. Type literal A type that represents a single value and nothing else. In the fourth case I explicitly annotated my variables with type literals, and in the sec‐ ond case TypeScript inferred a literal type for me because I used const instead of let or var. Because TypeScript knows that once a primitive is assigned with const its value will never change, it infers the most narrow type it can for that variable. That’s why in the second case TypeScript inferred c’s type as true instead of as boolean. To learn more about why TypeScript infers different types for let and const, jump ahead to “Type Widening” on page 122. We will revisit type literals throughout this book. They are a powerful language fea‐ ture that lets you squeeze out extra safety all over the place. Type literals make Type‐ Script unique in the language world and are something you should lord over your Java friends. number number is the set of all numbers: integers, floats, positives, negatives, Infinity, NaN, and so on. Numbers can do, well, numbery things, like addition (+), subtraction (-), modulo (%), and comparison (<). Let’s look at a few examples: let a = 1234 // number var b = Infinity * 0.10 // number const c = 5678 // 5678 let d = a < b // boolean let e: number = 100 // number let f: 26.218 = 26.218 // 26.218 let g: 26.218 = 10 // Error TS2322: Type '10' is not assignable // to type '26.218'. Like in the boolean example, there are four ways to type something as a number: 1. You can let TypeScript infer that your value is a number (a and b). 2. You can use const so TypeScript infers that your value is a specific number (c).2 3. You can tell TypeScript explicitly that your value is a number (e). 4. You can tell TypeScript explicitly that your value is a specific number (f and g). And just like with booleans, you’re usually going to let TypeScript infer the type for you (the first way). Once in a while you’ll do some clever programming that requires 22 | Chapter 3: All About Types
your number’s type to be restricted to a specific value (the second or fourth way). There is no good reason to explicitly type something as a number (the third way). When working with long numbers, use numeric separators to make those numbers easier to read. You can use numeric separa‐ tors in both type and value positions: let oneMillion = 1_000_000 // Equivalent to 1000000 let twoMillion: 2_000_000 = 2_000_000 bigint bigint is a newcomer to JavaScript and TypeScript: it lets you work with large inte‐ gers without running into rounding errors. While the number type can only represent whole numbers up to 253 , bigint can represent integers bigger than that too. The bigint type is the set of all BigInts, and supports things like addition (+), subtraction (-), multiplication (*), division (/), and comparison (<). Use it like this: let a = 1234n // bigint const b = 5678n // 5678n var c = a + b // bigint let d = a < 1235 // boolean let e = 88.5n // Error TS1353: A bigint literal must be an integer. let f: bigint = 100n // bigint let g: 100n = 100n // 100n let h: bigint = 100 // Error TS2322: Type '100' is not assignable // to type 'bigint'. Like with boolean and number, there are four ways to declare bigints. Try to let Type‐ Script infer your bigint’s type when you can. At the time of writing, bigint is not yet natively supported by every JavaScript engine. If your application relies on bigint, be careful to check whether or not it’s supported by your target plat‐ form. string string is the set of all strings and the things you can do with them like concatenate (+), slice (.slice), and so on. Let’s see some examples: let a = 'hello' // string var b = 'billy' // string const c = '!' // '!' let d = a + ' ' + b + c // string let e: string = 'zoom' // string let f: 'john' = 'john' // 'john' The ABCs of Types | 23
let g: 'john' = 'zoe' // Error TS2322: Type "zoe" is not assignable // to type "john". Like boolean and number, there are four ways to declare string types, and you should let TypeScript infer the type for you whenever you can. symbol symbol is a relatively new language feature that arrived with one of the latest major JavaScript revisions (ES2015). Symbols don’t come up often in practice; they are used as an alternative to string keys in objects and maps, in places where you want to be extra sure that people are using the right well-known key and didn’t accidentally set the key—think setting a default iterator for your object (Symbol.iterator), or over‐ riding at runtime whether or not your object is an instance of something (Sym bol.hasInstance). Symbols have the type symbol, and there isn’t all that much you can do with them: let a = Symbol('a') // symbol let b: symbol = Symbol('b') // symbol var c = a === b // boolean let d = a + 'x' // Error TS2469: The '+' operator cannot be applied // to type 'symbol'. The way Symbol('a') works in JavaScript is by creating a new symbol with the given name; that symbol is unique, and will not be equal (when compared with == or ===) to any other symbol (even if you create a second symbol with the same exact name!). Similarly to how the value 27 is inferred to be a number when declared with let but the specific number 27 when you declare it with const, symbols are inferred to be of type symbol but can be explicitly typed as unique symbol: const e = Symbol('e') // typeof e const f: unique symbol = Symbol('f') // typeof f let g: unique symbol = Symbol('f') // Error TS1332: A variable whose type is a // 'unique symbol' type must be 'const'. let h = e === e // boolean let i = e === f // Error TS2367: This condition will always return // 'false' since the types 'unique symbol' and // 'unique symbol' have no overlap. This example shows off a few ways to create unique symbols: 1. When you declare a new symbol and assign it to a const variable (not a let or var variable), TypeScript will infer its type as unique symbol. It will show up as typeof yourVariableName, not unique symbol, in your code editor. 2. You can explicitly annotate a const variable’s type as unique symbol. 3. A unique symbol is always equal to itself. 24 | Chapter 3: All About Types
4. TypeScript knows at compile time that a unique symbol will never be equal to any other unique symbol. Think of unique symbols like other literal types, like 1, true, or "literal". They’re a way to create a type that represents a particular inhabitant of symbol. Objects TypeScript’s object types specify the shapes of objects. Notably, they can’t tell the dif‐ ference between simple objects (like the kind you make with {}) and more compli‐ cated ones (the kind you create with new Blah). This is by design: JavaScript is generally structurally typed, so TypeScript favors that style of programming over a nominally typed style. Structural typing A style of programming where you just care that an object has certain properties, and not what its name is (nominal typing). Also called duck typing in some languages (or, not judging a book by its cover). There are a few ways to use types to describe objects in TypeScript. The first is to declare a value as an object: let a: object = { b: 'x' } What happens when you access b? a.b // Error TS2339: Property 'b' does not exist on type 'object'. Wait, that’s not very useful! What’s the point of typing something as an object if you can’t do anything with it? Why, that’s a great point, aspiring TypeScripter! In fact, object is a little narrower than any, but not by much. object doesn’t tell you a lot about the value it describes, just that the value is a JavaScript object (and that it’s not null). What if we leave off the explicit annotation, and let TypeScript do its thing? let a = { b: 'x' } // {b: string} a.b // string let b = { c: { The ABCs of Types | 25
Another Random Scribd Document with Unrelated Content
took more pleasure than in that of any of them, and whom, they knew, the late Constable had regarded as his only dangerous rival. It is certain that, had Bassompierre been so minded, he would have stood an excellent chance of succeeding to Luynes’s place as favourite, and that his elevation would have been well received, as he was exceedingly popular both at the Court and in the Army. But his epicurean wisdom rejected the idea of a life of gilded slavery; to be obliged to forgo the society of his “beautiful mistresses,” in order to dance attendance upon his youthful sovereign and make up his mind for him a dozen times a day, was not at all an attractive prospect to one who infinitely preferred pleasure to grandeur; the royal favour, without the responsibilities of power, was sufficient for him. The Cardinal de Retz, Schomberg and Puisieux had the advantage of being near the King at the time of the Constable’s death. The first two at once joined forces against Puisieux and “aspired to become all-powerful and to restrain the King from doing anything except on their advice.” They secured a decided success by persuading Louis XIII to bestow the vacant office of Keeper of the Seals upon De Vic, a counsellor of State, who was devoted to their interests, and then put their heads together to find a means of separating the King from Bassompierre, whom they regarded as a serious obstacle in the path of their ambition. Louis XIII arrived at Bordeaux on December 21, and shortly afterwards the two Ministers proposed to him to leave Bassompierre in Guienne as lieutenant-general of that province, in place of the Maréchal de Roquelaure, who was to be compensated for the loss of his post by a present of 200,000 livres and the government of Lectoure. Having obtained his Majesty’s consent to this arrangement, they sent Roucellaï to sound Bassompierre on the matter and “even offered to add to this charge that of marshal of France.” But Bassompierre preferred to wait upon events and to see into whose hands the management of affairs would fall, foreseeing that whoever might secure it would not be strong enough to maintain his position without support, and “being assured that he would be very pleased to have him for a friend, and to give him a larger share of the cake than they [Retz and Schomberg] were offering him.” “When the King spoke to me of the lieutenancy-general [of Guienne], I answered that I should esteem myself more happy to occupy the post of Colonel-General of the Swiss near his person than any other away from it;
that I was only just recovering from a severe illness which demanded three months’ repose, and that during that time I desired no other employment than that of my first office of Colonel-General. And to this his Majesty agreed.” Although foiled in this attempt to get Bassompierre out of the way, Retz and Schomberg presently returned to the charge, and having persuaded the Maréchal de Thémines to surrender the government of Béarn, in exchange for the lieutenancy-general of Guienne, offered it to Bassompierre. The government of Béarn, though, in the present circumstances, it could scarcely be regarded as a bed of roses, was a very honourable and lucrative post. But its acceptance would, of course, entail an almost complete separation from the King, and from—what was more important in Bassompierre’s estimation—the Court and Paris; and he therefore returned the same answer as he had in the case of Guienne. A day or two later, Bassompierre had the satisfaction of inflicting a sharp reverse upon the two Ministers. The Cardinal and Schomberg had urged the King to follow up the capture of Monheurt by the surprise of Castillon, on the Dordogne, which, they declared, could very easily be carried out and would have an excellent effect. Now, Castillon belonged to the Duc de Bouillon, who, at the outbreak of hostilities, had entered into a compact with Louis XIII, which stipulated that this and other towns within his jurisdiction should “remain in the service of the King, but without making war on those of the Religion”; while the King, on his side, promised that they should in no way be interfered with. To seize Castillon therefore would be a direct breach of this agreement, and could only be defended on the ground that the townsfolk had sent assistance to the Huguenots, of which there was no evidence of any value. Nevertheless, Louis XIII allowed himself to be persuaded by the two Ministers to consent to this being done, provided that the rest of the Council did not oppose it. When, however, the project was laid before the Council, Bassompierre rose and denounced it in a vigorous speech, in which he declared that, if executed, it would be a “great stain on the King’s honour and reputation,” after which he proceeded to give his Majesty some very wholesome advice on the danger of breaking his royal word. “Sire,” said he, “it is easy for a man to deceive a person who trusts him, but it is not easy to deceive a second time. A promise badly observed only
once deprives him who breaks it of the trust of the whole world.” And he stigmatized the counsel which had been given the King, of the source of which he pretended ignorance, as “interested, evil-intentioned and rash,” which, if followed, would probably result in driving Bouillon into rebellion, and with him numbers of Protestants who had hitherto remained neutral, since they would feel that it was impossible to trust the word of the King. One or two other members of the Council signified their agreement with the views expressed by Bassompierre, upon which the King announced that he had come to the same conclusion, to the great discomfiture of Retz and Schomberg, who were forced to recognise that their design of governing the young monarch was likely to prove a much more difficult task than they had bargained for. Louis XIII left Bordeaux on the last day of the year, and travelled by easy stages towards Paris. At Château-neuf-sur-Charente, where he arrived on January 6, 1622, another pretender to Luynes’s shoes appeared upon the scene, in the person of Condé. “Monsieur le Prince,” says Bassompierre, “who was extremely cunning and supple, was equally courteous to everyone, without inclining to any side, until he had perceived the tendency of the market. His design was to persuade the King to continue the Huguenot war, for three reasons, in my opinion: first, because of the ardent affection which he had for his religion and his hatred against the Huguenot party; secondly, because he thought that he could govern the King better in time of war than in time of peace, since he would undoubtedly be lieutenant-general of his army; and, lastly, in order to separate him from the Queen his mother, the Chancellor and the old Ministers, who were his antipathy.” In order to ascertain the state of the Court, Condé addressed himself to the Abbé Roucellaï, an adroit and insinuating personage, who had been in turn the protégé of Concini, the Queen-Mother and Luynes, and who, now that the Constable was dead, had decided to seek a new patron in Monsieur le Prince. The abbé told him that there were two parties at the Court. On one side, were the three Ministers, Retz, Schomberg and the new Keeper of the Seals, De Vic, “who desired to possess the King’s mind to the exclusion of everyone else”; on the other, the three marshals of France, Praslin,
Chaulnes, and Créquy[2] and some others, who were resolved not to submit to this. He added that the King conversed frequently with Bassompierre and appeared to have a rather high opinion of him, and that, if the latter had any ambition to succeed to the favour of the late Constable, it might very well be realised. That, however, did not seem to be his desire, “although he was disposed to accept the share in the King’s good graces which his services might merit.” Bassompierre and the Ministers, he told the prince, were “not always of the same opinion,” and only a few days before he had spoken very bitterly against them before his Majesty in a council. Condé then inquired if Bassompierre were in favour of continuing the war against the Huguenots, and Roucellaï answered that he had pressed Luynes to enter into negotiations with Rohan, from fear that the Royal army would be obliged to raise the siege of Montauban. As a result of this conversation, the prince sent Roucellaï to Bassompierre to inform him that he wished to speak to him and ascertain his views in regard to the war. Before seeing Bassompierre, however, Condé had an interview with the Ministers, whom he found in warlike mood, not because they believed that any useful purpose could be served by a continuance of this fratricidal strife, but for the same selfish reasons as he himself desired it, namely, “to keep the King so far as possible from Paris, in order the better to govern him.” He then approached Créquy, who answered that he was in favour of peace, provided that it could be obtained on advantageous and honourable terms. Bassompierre gave him a similar reply, when he spoke to him on the matter, and added that he would find Praslin and all other good servants of the King of the same opinion. “It is singular,” said the prince; “all you men of war, who ought to desire it, and can only make your way by means of it, want peace; and the lawyers and statesmen demand war.” “I answered,” says Bassompierre, “that I desired war, and that it ought to bring me fortune and advancement, but only on condition that it was for the service of the King and the good of the State; and that otherwise I should esteem myself a bad servant of the King and a bad Frenchman, if, for my own private advantage, I were to desire a thing which must cause both so much evil and prejudice.” After this sharp, if indirect, rebuke, Condé left him and told Roucellaï that, after sounding Créquy and Bassompierre, he found that he was likely to have more in common with the Ministers than with them.
During the remainder of the journey to Paris, skirmishes between the rival parties were of frequent occurrence, each doing everything possible to prejudice the King against the other. At Sauzé, where the Court arrived on the 10th, Bassompierre again scored at the expense of the Ministers. Louis XIII was about to sit down to cards with Bassompierre and Praslin, when the three Ministers were announced. “The King said to us as he saw them enter: ‘Mon Dieu, how tiresome these people are! When one is thinking of amusing oneself, they come to torment me, and most often they have nothing to tell me.’ I, who was very pleased to have the chance of giving them a rebuff in revenge for the ill turns they were doing me every day, said to the King: ‘What, Sire! Do these gentlemen come without being sent for by you, or without having first informed your Majesty that there is something of importance to deliberate upon, and then ask for your time?’ ‘No,’ said he, ‘they never inform me, and come when it pleases them, and most often when it does not please me, as they do now.’ ‘Jesus, Sire! is it possible?’ I replied. ‘That is to treat you like a scholar,
LOUIS XIII., KING OF FRANCE. From an engraving by Picart. and make themselves your tutors, who come to give you a lesson when it pleases them. You ought, Sire, to conduct your affairs like a King, and every day, on your arrival at the place where you purpose to spend the night, one of your Secretaries of State should come to tell you if there be any news of importance which requires the assembling of your Council, and then you should send for them to come to you, either at that same hour, or at one which will be most convenient to you. And, if they have anything to tell you, let them inform you of it first, and then send them word when they are to come to you. It was thus that the late King your father conducted his affairs, and your Majesty ought to do likewise; and if they [the Ministers] should come to you otherwise [i.e., without being sent for], to send them away, and to tell them of your intention firmly, once for all.’ “The King took the representations I had made him in very good part, and said that, from that moment, he would put my counsel into practice; and he went on talking to the Maréchal de Praslin and myself. When our
conversation had continued for some little time, Monsieur le Prince approached the King and said: ‘Sire, these gentlemen [the Ministers] await you to hold the council.’ The King turned to Monsieur le Prince with an angry countenance and exclaimed: ‘What council, Monsieur? I have not sent for them. I shall end by being their valet; they come when they please, and when it does not please me. Let them go away, if they wish to, and let them come only when I shall send for them; it is for them to consult my convenience and to send to inquire when that may be, and not for me to consult theirs. I desire that, at the end of each day’s journey, a Secretary of State should present himself at my lodging to inform me what news there is, and, if it be of importance, I will name a time to deliberate upon it; but I will never allow them to name it; for I am their master.’ “Monsieur le Prince was a little surprised at this response and was very curious to know from what shop it came. He went back to tell them [the Ministers], who requested him to inform the King that they were come merely to receive the honour of his commands, as courtiers, and not otherwise, and that if only his Majesty would speak a word to them, they would go away. The King did so, but very brusquely, and it was:— “‘Messieurs, I am going to play cards with this company.’ Upon which they made him a profound reverence and withdrew, very astonished.” The Ministers soon ascertained whom they had to thank for the very mortifying rebuff which they had received from the King, and were more incensed than ever against Bassompierre. The latter, who had been on very friendly terms with the Cardinal de Retz until his Eminence’s designs upon the King had brought their interests into collision, went to see him the next day and assured him that, so far as he himself was concerned, he was still his very humble servant. But he told him that he had no love for his colleagues, Schomberg and De Vic, and wished them to know it. The Cardinal begged him to be reconciled with them, but within forty-eight hours two incidents occurred which removed all hope of this. It happened that, the following evening, news arrived that the Maréchal de Roquelaure was dangerously ill and that his recovery was considered hopeless. “Upon which,” says Bassompierre, “these gentlemen [the three Ministers] and Monsieur le Prince went in a body to the King to demand the charge of marshal of France, which he [Roquelaure] had, for M. de Schomberg. The only answer which the King made them was to say: “And
Bassompierre—what shall he become?” This crude reply deeply affected M. de Schomberg, and from that day we ceased to speak to one another.”[3] The second incident, which followed closely upon the first, served to embitter still further the relations between these two gentlemen. “It happened on the morrow that the King only travelled one stage,[4] at which we [Créquy and himself] were annoyed, because we saw that these gentlemen [the Ministers] were purposely delaying the King’s arrival, thinking, if time were allowed them, to usurp the authority before he had seen the Queen his mother and the old Ministers. The Maréchal de Créquy and I, while warming ourselves in the King’s wardrobe, complained of these short journeys, upon which the Comte de la Roche-guyon told us that they were made out of consideration for the French and Swiss Guards, who otherwise would be unable to follow us. We said then that this consideration ought not to occasion such a long delay; that we, who were respectively in command of the two regiments of Guards, did not complain, that the Guards would march so far as the King pleased, and that we could make them do what we wished. Out of these last words, which were reported to the Ministers, they proceeded to compound three dishes for the King, saying that we boasted of making the two regiments of Guards do what we wished, and that we could turn them in whatever direction we pleased. They attacked the King on his weak side, and he was angry at seeing that we were compromising his authority. “The evening before he arrived at Poitiers, he told me that he desired to speak to me on the following morning, and said to me: ‘I promised to tell you all that might be said to me concerning you. That is why, since it has been reported to me that you were boasting of being able to persuade the Swiss to do all that you wished, and even against my service, I desired to make you understand that I do not approve of such discourse being held, and less by you than by another, seeing that I have always had entire confidence in you.’ “‘God be praised, Sire,’ I answered, ‘that my enemies, seeking every means to injure me, are unable to find anything save what is easy for me to avert and bring to naught. This accusation is of that quality, and you can learn the truth from their own mouths, although it is but little accustomed to issue from them. Ask them, Sire, on what subject I said that I would make the Swiss do what I wished, and if they do not tell you that it was on that of
their making long or short marches, about which M. de Créquy and I were complaining to one another, since they make arrangements for your Majesty to travel a shorter distance each day to return to Paris than a parish procession would cover, I am willing to lose my life. And your Majesty can judge whether that touches you or not, and whether you ought to regard this discourse as a boast of being able to employ the Swiss against your service.’” The King did not accept Bassompierre’s proposal to confront him with his accusers; but he sent for two valets of his wardrobe, who had been present during the conversation between him and Créquy, and questioned them in his presence. They confirmed what Bassompierre had just told him, and his Majesty expressed himself satisfied that he had spoken the truth. This clumsy attempt to injure Bassompierre recoiled upon its authors in a manner that was distinctly embarrassing for them. A few days later, when the King was at Châtellerault, the Ministers proposed that he should travel on the following day only so far as La Haye-Descartes, on the right bank of the Creuse, a very short day’s journey. Louis, however, announced his intention of going on to Sainte-Maure, adding significantly that it seemed to him that, if they could have their way, he would not reach Paris for three months. These squabbles between the jealous and spiteful courtiers and Ministers who surrounded Louis XIII, to all appearance so trifling, were in reality of great political importance. For they were all manœuvres in the struggle to dominate the indolent and fickle mind, and, with it, the policy, of this young monarch, who, while so punctilious in exacting all the respect which he considered due to his royal dignity, was ready to surrender the sovereign authority to the favourite of the moment. And upon the result of that struggle hung the destinies, not only of France, but of Europe. On January 27, Louis XIII arrived in Paris, where Marie de’ Medici was awaiting him. The meeting between them was most affectionate. Marie expressed the greatest joy at seeing her son return to his capital so well in health and now indeed the master; and the King replied that he intended to prove to everyone that never did son love or honour his mother more. Marie believed him too easily. Louis XIII was twenty-one and not nearly so manageable as he had been as a lad; and he feared the authoritative temper
of Richelieu, of whom the Nuncio Corsini wrote to Gregory XV that he was “of a character to tyrannise over both the King and his mother.” Besides, to re-establish her influence over her son it was necessary for the Queen- Mother to keep him near her, and circumstances were to render this impossible. Notwithstanding that the country was rent by civil war, and that so many distinguished families were in mourning for relatives fallen before Montauban, the winter in Paris seems to have been as gay as ever. “The Court was very beautiful, and the ladies also,” says Bassompierre, “and during the Carnival several fine comedies and grand ballets were performed.” In the middle of March, however, a most unfortunate incident occurred, which cast a gloom over both Court and capital. Early in 1622, to the great joy of the nation, the Queen had been declared pregnant. Prayers were offered up in all the churches in France for her safe delivery, and all those about her Majesty’s person were strictly enjoined not to allow her to exert herself, to which instructions, however, they unfortunately appear to have paid but little heed. One evening, Anne of Austria and a party of courtiers, amongst whom were the widowed Duchesse de Luynes and Mlle. de Verneuil, went to spend the evening with the Princesse de Condé, who was ill and confined to her bed. On their way back to the Queen’s apartments, they were passing through the grande salle of the Louvre, when Madame de Luynes and Mlle. de Verneuil seized their royal mistress by the arms and began to run. They had not, however, gone many paces when the Queen tripped and fell on her face. A few hours later, to the general dismay, it was known that her Majesty had had a miscarriage. Louis XIII was furiously indignant, as well he might be, and wrote to the two delinquents with his own hand, ordering them to retire from Court. It is probable that the disgrace of Madame la Connétable, against whom, as we know, his Majesty already had a grievance, might have lasted some considerable time, had not her marriage with the Duc de Chevreuse, who stood high in the King’s favour, paved the way for her return.
CHAPTER XXVII Question of the Huguenot War the principal subject of contention between the two parties —Condé and the Ministers demand its continuance—Marie de’ Medici, prompted by Richelieu, advocates peace—Secret negotiations of Louis XIII with the Huguenot leaders —Soubise’s offensive in the West obliges the King to continue the war—Louis XIII advances against the Huguenot chief, who has established himself in the Île de Rié— Condé accuses Bassompierre of “desiring to prevent him from acquiring glory”— Courage of the King—Passage of the Royal army from the Île du Perrier to the Île de Rié —Total defeat of Soubise—Siege of Royan—The King in the trenches—His remarkable coolness and intrepidity under fire—Capitulation of Royan—The Marquis de la Force created a marshal of France—Conversation between Louis XIII and Bassompierre— Diplomatic speech of the latter. Meantime, the struggle between the two parties, which had begun on the journey from Bordeaux to Paris, continued at the Louvre. Condé and his allies were unable to prevent the Queen-Mother from entering the Council, but they succeeded in excluding the man who possessed her mind. Richelieu spoke through her mouth, however, and those who remembered her regency were astonished at the prudence, address, and firmness which she now displayed. The war against the Huguenots was the principal subject of contention. Marie de’ Medici, under the influence of Richelieu, the old Ministers the Chancellor Sillery and Jeannin, Puisieux, and the generals, wished for peace; Condé and the new Ministers demanded the continuance of the war. Condé saw in the war the means of separating the King from his mother, and commanding the army in the name of Louis XIII. A superstitious hope made him particularly anxious to have large military forces at his disposal. An astrologer had predicted to him that he would become King at the age of thirty-four, and he was now in his thirty-fourth year. He desired, therefore, to prove his devotion to the Catholic religion, and to be in a position to seize the crown at the date when Louis XIII and his younger brother were apparently destined to die. Marie brought to the Council the arguments with which Richelieu had furnished her on the grave situation of external affairs. The House of Austria, she pointed out, was everywhere aggressive and everywhere successful. In Germany, the Empire had reduced Bohemia to submission.
The unfortunate Elector Palatine, deprived of the Upper Palatinate by Maximilian of Bavaria, and of the Lower Palatinate by Tilly, General of the Catholic League, and Gonzalvo de Cordoba, commander of the Spanish forces, had been obliged to take refuge in Holland. Philip IV, on the expiration of the twelve years’ truce with Holland in 1621, had called upon the Dutch to acknowledge his supremacy, and, on their refusal, had attacked them. The Spaniards mocked at the Treaty of Madrid, and, so far from evacuating the Valtellina, as they had engaged to do, had invaded the country of the Grisons, in concert with the Archduke Leopold, and obliged them to submit to a humiliating treaty which deprived them of the suzerainty of the Valtellina. Prompted by Richelieu, Marie urged upon the Council the imperative necessity of pacifying France, in order to be in a position to intervene in the affairs of Europe and arrest the alarming progress which the House of Austria was making. “To enter into a civil war,” said she, “is not the road to arrive at it, as was manifest during the siege of Montauban, when, in place of executing the Treaty of Madrid, they [the Spaniards] pushed their armies further and advanced by much their design to arrive at the monarchy of Europe. Although assuredly it is better to perish rather than abate anything of the royal dignity, it seems that it [the dignity] is preserved, if peace and the pardon of their crimes is given to them [the Huguenots], without restoring to them any of the places of which they have been deprived.” Condé and his allies pretended, on the contrary, that it was necessary before everything, and at all costs, to subdue the internal enemy and to check the audacity of the Huguenots, immensely encouraged by the successful resistance of Montauban. La Force and his sons had resumed hostilities in Guienne, and many places in that province which had submitted to the King had revolted anew. In Lower Languedoc, masters of Nîmes, Montpellier, Uzès, Privas, and a number of smaller towns, the assembly of the “circle,” had ordered or, at any rate, authorised, the most disgraceful excesses, and between thirty and forty churches, amongst which were some of the finest monuments of the Middle Ages, had been ruined. In the West, the Rochellois were masters of the sea; Saint-Luc, who had vainly endeavoured to make head against them, was blockaded in the port of Brouage; and a multitude of privateers preyed upon the commerce of the Atlantic coast.
At the beginning of 1622, the Rochellois and the predatory nobles who made common cause with them conceived the bold project of occupying the mouths of the Loire and the Gironde, in order to hold all the commerce of those two rivers to ransom. The revolt of Royan, on the right bank of the Gironde, and the occupation of two other strong points had already resulted in the virtual blockade of that river; while Soubise, violating the oath which he had taken at the capitulation of Saint-Jean-d’Angély not to bear arms again against his sovereign, charged himself with the Loire, descended with a considerable force on Sables d’Olonne, in order to raise the Protestants of Poitou, and overran all the country up to the suburbs of Nantes. Thus tricked by the Spaniards and braved by the Protestants, Louis XIII had to choose between his enemies. For a time he appeared inclined to listen to the advice of his mother—or rather of Richelieu—and, unknown to Condé and his supporters, authorised Lesdiguières to negotiate with Rohan. “And that nothing might be revealed,” says Bassompierre, “save to M. de Puisieux and myself, whom he commanded to keep the affair very secret, he wished that M. des Lesdiguières sent duplicate despatches; one copy to be read and deliberated upon in the Council; the other, which was private and addressed to M. de Puisieux, to be communicated only to the King, who informed me of its contents.” The negotiations progressed so far that Louis promised to receive a deputation from the Reformed churches, and threatened the Spanish Ambassador to go to Lyons and organise an army to march to the assistance of the Grisons, if Spain did not forthwith withdraw from their country and the Valtellina. But the progress of Soubise and the disobedience of d’Épernon, who declined to send troops from his governments of Saintonge and the Angoumois to the assistance of the hard- pressed Royalists of Poitou, gave the victory to Condé and his adherents; the King decided to march in person against Soubise, and, on March 20, without waiting for the arrival of the Protestant deputies, he left Paris for Orléans, accompanied by the Queen-Mother, who was determined to keep within reach of him so long as she could. From Orléans, the King, still accompanied by Marie, proceeded to Blois, and thence by water to Nantes, where the army was to assemble, and where on the 11th he was joined by Bassompierre, who had been summoned by courier from Paris. On his arrival at Nantes, Louis XIII learned that Soubise was endeavouring to establish himself in the Île de Rié, a maritime district of
Lower Poitou, separated from the mainland by vast salt marshes and small rivers, which at high tide the sea rendered impassable. If the Huguenot leader were permitted to entrench himself there, it was a position from which it would be exceedingly difficult to dislodge him; but this the King resolved not to allow him time to do; and, leaving the Queen-Mother, who had fallen ill, at Nantes, like a true son of Henri IV, he marched at once upon the enemy. The Royal army consisted of from 10,000 to 12,000 men; that of Soubise from 6,000 to 7,000; but the latter had the advantage of position and seven pieces of cannon; while the attacking force was, of course, unable to transport its artillery across the marshes. The enterprise would therefore have been a hazardous one, with a watchful and resolute enemy to contend with. On this occasion, however, Soubise showed neither the vigilance of a general nor the courage of a soldier. The approach of the enemy much sooner than he had foreseen appears to have disconcerted his plans altogether, and, instead of attempting to defend the approaches to the Île de Rié, he thought only of re-embarking his troops in a squadron of vessels which he had at his disposal, and making his escape with the plunder he had collected to La Rochelle. In the afternoon of April 14, Marillac, with a small force of infantry, occupied the Île du Perrier, adjoining the Île de Rié, and early on the following morning Bassompierre was ordered by Condé to follow with the rest of the infantry. Condé then proposed that they should ford an arm of the sea “wide as the Marne,” which separated the islands of Perrier and Rié, and where at low tide, which would be at midday, the peasants had told him, the water would be only waist-deep. Bassompierre, however, protested against this, pointing out that, if the enemy offered the least opposition to their passage, the tide would rise before half the troops had crossed, and even if they were allowed to cross unopposed, they would find themselves at a great disadvantage without cavalry or cannon. He added that, apart from these considerations, he ought certainly to await the arrival of the King. “For if you defeat M. de Soubise,” said he, “he [the King] will take it ill that you have not shared the honour of the victory with him; and, if some reverse befalls you, he will blame your precipitation, and will accuse you of not having wished or deigned to wait for him.” Monsieur le Prince took this remonstrance in very bad part, and declared that he saw plainly that Bassompierre was “of the cabal who desired to
prevent him from acquiring glory.” But he sent him to the King to beg him to come at once with the cavalry, and when his Majesty arrived on the scene, it was decided to wait until midnight and to cross to the Île de Rié at another spot, where they were informed there would be less water. In the course of the evening, Louis XIII displayed for the first time that cool courage which he invariably afterwards showed in war, and which, if it had been combined with the same degree of moral resolution, would have made him a really remarkable man:— “While the King, stretched on a miserable bed,” says Bassompierre, “was consulting with us about the passage, a great alarm spread throughout the camp that the enemy was upon us; and, in an instant, fifty persons rushed into the King’s chamber, who declared that the enemy was at hand. I knew well that this was impossible, since it was high tide, and they could not pass. Instead, therefore, of being alarmed, I wished to see how the King would take it, in order that I might regulate the proposals which I might in future have to make to him, according to the firmness or agitation which he displayed. This young prince, who was lying down on the bed, sat up on hearing this rumour, and, with a countenance more animated than usual, said to them: ‘Gentlemen, the alarm is without, and not in my chamber, as you see; it is there you must go.’ And, at the same time, he said to me: ‘Go as quickly as you can to the Bridge of Avrouet, and send me your news promptly. You, Zamet, go out and find Monsieur le Prince, and M. de Praslin and Marillac will stay with me. I shall arm myself and place myself at the head of my Guards.’ I was delighted to see the confidence and judgment of a man of his age so mature and so perfect. The alarm was, as I supposed, a false one, arising from a very trifling incident.” All the arrangements for the passage of the army had been entrusted to Bassompierre. The troops assembled at ten o’clock, and a little before midnight the order to advance was given. At the spot where the Guards were to cross, however, the water was so deep that they sent to inform Bassompierre that it was impossible to pass. He went there, and finding that it would be a very difficult undertaking, led them to another ford, by which he crossed himself to the Île de Rié, and saw no sign of any enemy. He returned and reported that the ford was practicable and that their passage would be unopposed, and the whole army passed without mishap; though when Bassompierre crossed for the second time, at the head of the
rearguard, the tide was beginning to rise, and the water was nearly up to his chin.[5] On reaching the shore, the troops encamped and lighted a great number of fires to dry their clothes. At daybreak they were formed in order of battle, and, after a march of about two leagues, came in sight of the enemy. Soubise and his cavalry, to the number of five or six hundred, fled at once in the direction of La Rochelle, without striking a blow. Part of the infantry had already embarked in the launches that had arrived to take them off; the rest threw down their arms and demanded quarter. But this was refused to the majority of them, and more than 1,500 were shot or cut down in cold blood; while as many more were taken prisoners and sent to the galleys. The rest fled across the marshes, in which some of them were drowned, while many others were slain by the troops of La Rochefoucauld, governor of Poitou, or by the peasants, furious at the devastation which the Huguenots had committed. Only some four hundred succeeded in effecting their escape and making their way to La Rochelle. Leaving a force under the Comte de Soissons to watch La Rochelle on the land side, while Guise was directed to blockade it by sea, Louis XIII marched southwards, with the intention of raising the blockade of the Gironde by the reduction of Royan. During the siege, the King gave further proofs of that courage and presence of mind which Bassompierre had admired before the attack on the Île de Rié. “That same evening I went to the King in his quarters, and he told me that he was coming to see our trench at five o’clock the next morning ... and desired me to await him at the commencement of it. He came, accompanied by M. d’Épernon and M. de Schomberg. It was the first time he had ever been in the trenches, and he did me the honour to say to me: ‘Bassompierre, I am a novice here; tell me what I must do, so that I may not make mistakes.’ In this I found little difficulty, for he was more prodigal of his safety than any of us would have been, and mounted three or four times on to the banquette of the trench, where he was exposed to the fire of the enemy, to reconnoitre. And he stayed there so long that we trembled at the danger he was incurring, which he braved with more coolness and intrepidity than an old captain would have shown, and gave orders for the work of the following night as though he had been an engineer. While he was returning, I saw him do what pleased me extremely. After we had
remounted our horses, at a certain passage which the enemy knew, they fired a cannon-shot, which passed two feet above the head of the King, who was talking to M. d’Épernon. I was riding in front of him, and turned round, fearing that the shot might have struck him. ‘Mon Dieu, Sire,’ I exclaimed, ‘that ball was near killing you!’ ‘No, not me,’ said he, ‘but M. d’Épernon.’ He neither started nor lowered his head, as so many others would have done; and afterwards, perceiving that some of those who accompanied him had drawn aside, he said to them: ‘What! Are you afraid that they will fire again? They will have to reload.’ I have witnessed many and various actions of the King in several perilous situations, and I can affirm, without flattery or adulation, that I have never seen a man, not to say a king, who was more courageous than he was. The late King, his father, though, as everyone knows, celebrated for his valour, did not display a like intrepidity.” It is not the degree, but the kind of courage, which is remarkable at his age. Bassompierre, however, relates an instance of equal coolness in a boy, who had not the same strong motive to self-possession as was furnished by the consciousness of being the object of the whole army’s attention: “The enemy had constructed a barricade in their fosse, on the side of the sea, and a palisade, which hindered us from being entirely masters of their fosse. I sent my volunteer, a young lad of sixteen, to reconnoitre it. This lad had, the previous year, executed with other camp-boys the most hazardous works at the siege of Montauban, which the soldiers refused to undertake. He had received several wounds, amongst others a musket-ball through the body, of which I got him cured. This young rogue undertook a number of dangerous works by the piece, and the camp-boys worked under him and made a great deal of money. He went to reconnoitre this barricade with the same bearing and as much boldness as the best sergeant in the army; and after getting a musket-ball through his breeches and another through the brim of his hat, returned to us and made his report, which was very judicious.” Royan capitulated on May 11, and shortly afterwards La Force surrendered the town of Sainte-Foy and returned to his allegiance, in return for the bâton of Marshal of France. Louis XIII, who had been given to understand that both Bassompierre and Schomberg were deeply mortified that a rebel should have been created a marshal before either of them, sent
for the former and said to him: “Bassompierre, I know that you are angry that I am making M. de La Force Marshal of France, and that you and M. de Schomberg complain of it, and with reason; but it is not I who am the cause of it, so much as Monsieur le Prince, who counselled me to do it, for the good of my affairs, and in order to leave nothing behind me in Guienne which might prevent me passing promptly into Languedoc. Nevertheless, be sure that what you desire I shall do for you, whom I love and hold as my good and faithful servant.” Bassompierre tells us that at that time he had no particular desire for the office of marshal, “since, in his opinion, it was that of an old man, while he wished to play the part of a gallant of the Court for some years longer.” He therefore assured his Majesty that he had been entirely misinformed, and that, so far from being annoyed at La Force’s appointment, he regarded it as a most proper one, since he was an old man and a soldier of great experience, who had been promised the bâton by the late King and would have received it, if Henri IV had lived another month; that, although he had been a rebel, he was one no longer; and that it was “a signal example of the kindness of the King to forget the faults of his servants, in order to remember and recompense their merits and their services.” And he added that he did not aspire to the office of marshal or any other charge, unless his Majesty “out of pure kindness and desire to recognise his service,” wished to confer it upon him, and that he “very humbly besought him never to allow any consideration for him to prevent him doing what he judged to be for the good of his service.” This diplomatic speech greatly pleased the King, who thanked Bassompierre and told him that he might rely on him to advance his interests. He then sent for Schomberg, who, much less tactful than his colleague, pressed his Majesty to make him a marshal conjointly with La Force, and proposed that Bassompierre should be created one also, “though this was chiefly in order to strengthen his own request.”
CHAPTER XXVIII Condé and his allies offer to secure for Bassompierre the position of favourite, if he will join forces with them to bring about the fall of Puisieux—Refusal of Bassompierre— Condé complains to Louis XIII of Bassompierre’s hostility to him—Bassompierre informs the King of the proposal which has been made him—Louis XIII orders Monsieur le Prince to be reconciled with Bassompierre—Siege of Négrepelisse—The town is taken by storm—Terrible fate of the garrison and the inhabitants—Fresh differences between Condé and Bassompierre—Discomfiture of Monsieur le Prince—Bassompierre placed temporarily in command of the Royal army, captures the towns of Carmain and Cuq- Toulza—Offer of Bassompierre to resign his claim to the marshal’s bâton in favour of Schomberg—Surrender of Lunel—Massacre of the garrison by disbanded soldiers of the Royal army—Bassompierre causes eight of the latter to be hanged—Lunel in danger of being destroyed by fire with all within its walls—Bassompierre, by his presence of mind, saves the situation—Schomberg and Bassompierre—The latter is promised the marshal’s bâton. At Moissac, where Louis XIII arrived in the first week in June, Condé approached Bassompierre and invited him to meet him “in a kind of chapel which is in the cloister of the abbey,” as he desired to confer with him on a matter of great importance. Thither Bassompierre repaired and found the prince in the company of his allies, Retz and Schomberg. All three forthwith began to inveigh against Puisieux, whose presumption, they declared, they were no longer able to endure. Although only a Secretary of State, he was admitted to greater intimacy with the King than Monsieur le Prince himself, sought to prejudice his Majesty against those with whom he was not on good terms, conducted separate negotiations, which he declined to communicate to them, and prevented the execution of the decisions of the Council, if he had not previously approved of them. Since the death of the late Constable, they had, they said, endeavoured “to prevent the King from embarking in a new affection,” and they were of opinion that it would be better for his Majesty to have no favourite. “However, since they saw that his inclination was to be dominated by someone, they preferred that it should be by a brave man, of high birth and esteemed for his knowledge of the arts of peace as well as of those of war, rather than by a man of the pen like M. de Puisieux, who would turn everything upside down; and that they were all resolved to conspire to bring
about his ruin, as they were to assist in the aggrandisement of my fortune, and to persuade the King, who was already favourably inclined towards me, to favour me entirely with the honour of his good graces, provided that I were willing to promise them two things: the one, to co-operate with them to ruin M. de Puisieux and to detach myself entirely from his friendship; the other, to associate myself entirely with them and combine our designs and counsels, in the first place, for the good of the King’s service, in the second, for our common interest and preservation. And they begged me to come to a prompt decision upon this matter and to acquaint them with it.” Bassompierre felt quite certain that the proposal which had just been made to him was nothing but a skilfully-baited trap, and that the intention of Condé and his friends was “to penetrate his design and then to reveal it to the King, and that they desired to make use of him to ruin M. de Puisieux, and afterwards with greater facility to ruin him.” “I accordingly replied that I was unable to understand what necessity there was for the King to have a favourite, since he had dispensed with one so easily for eight months; that his favourites ought to be his mother, his brother, his relatives and his good servants, wherein he would be following the example of the King his father, and that if some fatality inclined him to have one, the choice and the election ought to be left to him; that I had never heard tell of any prince who took his favourites according to the decrees of his council; but that, however that might be, it would not be I who would occupy that place, because I did not deserve it; because, also, the King would not wish to honour me with it, and because, finally, I would not accept it; that I aspired to a moderate degree of favour, and a fortune of the same kind acquired by my virtue and by my merit, and which might be securely preserved; that my lavish expenditure, and the little care I had taken up to the present to amass wealth, were sufficient proofs that I aspired rather to glory than to profit; that I wished to seek a moderate and a secure fortune, and despised favour to such a degree that, if it were lying on the ground before me, I should not condescend to stoop and pick it up; and that such was my unalterable resolution, which did not allow me to take advantage of their good-will towards me, for which I rendered them very humble thanks.”
As for their complaints about Puisieux, he said, it seemed to him that they were really complaining of the King and questioning his Majesty’s right to confer privately with, and demand advice from, whichever of his Ministers he pleased. Puisieux was his [Bassompierre’s] friend, and had always behaved as such, and, so long as he continued to do so, he declined to be a party to any intrigue against him. Condé then warned Bassompierre that a time might come when he would regret having lost his friendship and that of his allies in order to preserve that of Puisieux; to which Bassompierre replied that he would be “extraordinarily grieved to lose their good graces, but that the consolation would remain to him of not having lost them through any fault of his own, and that he would never purchase those of anyone at the price of his reputation.” That evening, Louis XIII decided to send a body of two hundred cavalry to scout in the direction of Montauban, and Valençay, who was lieutenant of Condé’s company of gensdarmes, asked to be allowed to go, and to take with him both his own men and Monsieur le Prince’s company of light horse; and to this the King consented. Condé was not at the council of war, and did not learn of what had been done until later in the evening, when he was extremely angry and went to the King to complain that an affront had been put upon him by sending his two companies of horse away without his knowledge, and that he felt quite certain that it was Bassompierre who had suggested it. The King assured him that Bassompierre had had nothing to do with the affair, and that Valençay had himself asked for the commission, which he had given him, never imagining that Monsieur le Prince would take it ill. Condé, however, insisted that Bassompierre must have been at the bottom of it, and declared that he was hostile to him. When he had gone, the King sent for Bassompierre and told him of what the prince had said, upon which he deemed it advisable to inform his Majesty of the proposal which Condé had made him that morning in the chapel. “But,” he says, “as it is very dangerous to be in the disfavour of a person of that rank who is your general, I begged the King very humbly either to reconcile us or to permit me to retire, since I did not wish to draw his hatred and his anger upon me.” This the King promised to do, and the next evening, when the army had encamped at Villemode, near Montauban, he came into the camp, and having praised Bassompierre for the arrangements which he had made, he
turned to Condé and said: “Monsieur, yesterday you were angry with him without cause, and you can learn from Valençay whether Bassompierre was in any way responsible for his being sent away. I beg you, for love of me, to live on good terms with him, for I assure you he is your servant; and, if he were lost to this army, you know yourself whether it would be our fault.” Condé promised to do as the King desired, and the same evening offered his apologies to Bassompierre, who begged him to regard him as his very humble servant, and that “when he happened to have any reason to be displeased with him, to do him the honour of telling him of it, and, if he did not give him satisfaction in the matter, to be angry with him with all his soul, and not before.” On the following day—June 8—the army arrived before Négrepelisse, a little town on the left bank of the Aveyron. Louis XIII and his whole army were bitterly incensed against the inhabitants of Négrepelisse, who, one night during the previous winter, had revolted and massacred four hundred men of the Vaillac Regiment who had been placed in garrison there; while a report was current among the soldiers that, during the siege of Montauban, the sick and wounded of the Royal army who had been transported thither had been poisoned. However, as the town was believed to have returned to its allegiance, provided they admitted the King, there would not appear to have been any intention of punishing the inhabitants. But when the quartermaster who had been charged to select suitable quarters for his Majesty, approached the gates, he found them closed, and was received with a volley of musket-shots. On learning of what had occurred, the King ordered Bassompierre, who was with the advance-guard, to invest the town, which he proceeded to do; but, on going forward to reconnoitre the place with Praslin and Chevreuse, he had a narrow escape of his life, being fired upon from a distance of twenty paces by a party of the enemy, whom he had mistaken for some of his own men. “There was not in Négrepelisse,” says Bassompierre, “anything better than a musket; no munitions of war save what each inhabitant might have had to go out shooting; no foreign soldier, no chief to command them; and the place, though it might have offered some resistance to a provincial force, was quite incapable of resisting a Royal army. Nevertheless, the inhabitants would neither consent to surrender nor even to parley.”
The probable explanation is that the townsfolk were convinced that the King was bent upon their destruction, and that no terms which he might consent to give them would be observed; and that they had therefore determined to sell their lives for what they might be worth. On the 9th, a battery of seven cannon was got into position close to the walls, and, although the enemy’s musketry-fire was very effective, and caused many casualties amongst the gunners, by the following morning a considerable breach had been made. The besieged endeavoured to repair it by a barricade of carts, but this was of little avail, and the town was quickly taken by assault. Louis XIII, infuriated by the obstinacy of the inhabitants, had given orders that they were to be treated as they had treated his soldiers some months before, and every man capable of bearing arms was put to the sword, with the exception of a few who succeeded in escaping into the château. The troops exceeded the pitiless orders of the King, and the majority of the women were violated and many murdered, together with their children; while the town was pillaged and burned almost to the ground. The officers appear to have done their best to protect the women and to save the town; but, as so often happened in those days when places were taken by assault, the soldiers were quite out of hand, and it was impossible to restrain them.[6] The château held out until the following day, when it surrendered at discretion, and twelve or fifteen of those found there were taken and hanged. The reconciliation between Bassompierre and Condé was of very short duration, for, a day or two later, the prince accused him in a council of war of questioning the orders which were given him. Bassompierre retorted that he had a right to his opinion, and that “if his mouth were to be closed, he should retire from the Service. The King thereupon took his part, and was very angry with Monsieur le Prince.” Further differences arose between them respecting the investment of Saint-Antonin, and, as Condé refused to be guided by his advice, Bassompierre begged to be permitted not to serve during the siege, and his request was granted. Marillac was then appointed to the temporary command of Bassompierre’s troops; but the officers of the Guards refused to take their orders from him, as did those of the Navarre Regiment. Condé was furious and, going to the King, accused Bassompierre of “making cabals and
mutinies in his army,” and said that he “deserved punishment and even death.” And that gentleman happening to enter the royal presence a few moments later, he denounced him to his face. Bassompierre denied the charge, and said that the refusal of the officers of the Guards and of Navarre to serve under Marillac was not due to any action on his part, but to the poor opinion they entertained of Marillac’s military capabilities, and that if some other officer were appointed, they would obey him readily enough. With this explanation Louis XIII professed himself satisfied, and Monsieur le Prince retired discomfited. If we are to believe Bassompierre, Condé would appear to have bungled the siege of Saint-Antonin pretty badly, and an imprudent attempt to take the place by assault was repulsed with heavy loss. However, on June 22 the town surrendered. A few days later, Bassompierre and the prince again came into collision. Condé had proposed in the Council to attack Carmain, a nest of Huguenots which was a great annoyance to the people of Toulouse, who had petitioned that its reduction should be undertaken;[7] but Bassompierre objected that to conquer these small places was to waste time which might be more usefully employed in besieging important strongholds of the enemy like Nîmes and Montpellier. It was decided to follow his advice, whereat “Monsieur le Prince’s bile was stirred against him,” and he left the Council in anger, complaining loudly that Bassompierre had prevented Carmain from being invested. Some Huguenot gentlemen happening to overhear him, sent to inform the authorities of that town that the Royal army had no intention of laying siege to it, in consequence of which a body of 500 men who were on their way from Puylaurens to reinforce the garrison received orders to return. Bassompierre, who had been ordered to lead the army to Castelnaudary, while the King and Condé went to visit Toulouse, learned of the return of this reinforcement, and aware that, deprived of its assistance, the people of Carmain would probably consider themselves incapable of withstanding a siege, determined to make an attempt to trick them into surrender. He accordingly appeared before the town, with all the paraphernalia for a siege: carts loaded with gabions, platforms for the batteries, and so forth, although he, of course, had no intention of undertaking it, since he had not received any orders to that effect, and, besides, had only two siege-guns with him. He then summoned it to surrender, vowing to make a terrible example of it in the event of a refusal,
and to treat it as Négrepelisse had been treated; and the inhabitants, completely deceived, offered to parley forthwith, and early on the following morning, terms of capitulation having been arranged, the place surrendered (June 30). The previous night part of the Piedmont Regiment, which Bassompierre had detached against the neighbouring town of Cuq-Toulza, had carried that place by assault, after blowing in the gate with a petard. So that within a few hours two towns had been taken, one of them without a blow being struck. Not a little elated by this double success, Bassompierre placed the army in charge of Valençay, and repaired to Toulouse to report to the King. “I arrived,” says he, “at the moment when the King was holding his council and was reprimanding Monsieur le Prince, because, when the Parlement and aldermen of Toulouse had come to do him homage, Monsieur le Prince had said that the cowardice of M. de Bassompierre had prevented the King from attacking Carmain, as, though he had counselled him to do it, I had dissuaded him. When the King was informed that I was at the door, he wondered what could have caused me to quit the army; but, when he ordered me to be admitted, I told him that I wished to bring him myself the news of the capture of Carmain and Cuq and to receive his commands upon other matters which I wished to propose to him. Then Monsieur le Prince rose and came to embrace me, telling me that he had done wrong to say what he had said, and that he would repair it by saying much good of me.... It is impossible to describe the joy with which the people of Toulouse received the news of this capture. They caused a splendid lodging to be made ready for me; and the aldermen came to thank me, and to invite me to dine on the morrow at the Hôtel-de-Ville, where they would hold a grand assembly for love of me, and a ball to follow. But I begged them to excuse me, on the ground that it was necessary for me to return promptly to the army.” Bassompierre returned to the army accompanied by Praslin, who took over the command. The following day he met with what might have been a very severe accident, his horse stumbling and falling into a ditch on top of him. However, he escaped with nothing worse than a badly bruised foot. On July 2, the army reached Castelnaudary, having snapped up the little town of Le Mas-Saintes-Puelles on the way, and on the 5th the King joined it. His
Majesty was unwell, suffering, says his physician Hérouard, from “sore throat, a cold, and a relaxed uvula,” and he remained for some days at Castelnaudary and kept Bassompierre with him; while the army under Praslin continued its march into Lower Languedoc. Meantime, Lesdiguières, to whom, after the death of Luynes, Louis XIII had promised the office of Constable, provided he would renounce the Reformed faith, had sent to inform the King that he was about to be received into the Catholic Church. His elevation would entail a vacancy among the marshals, and the King sent for Bassompierre and Schomberg, who had also remained at Castelnaudary, and told them that, so soon as another occurred, he would create them both marshals, but that he did not wish to promote one before the other, as he considered that their claims were equal. Schomberg, however, pressed the King to promote both Bassompierre and himself forthwith, pointing out that they could render him more useful service as marshals of France in the approaching campaign in Lower Languedoc, and that when there was another vacancy, his Majesty could leave it unfilled, which would come to the same thing. Perceiving that the King seemed very reluctant to take this course, though, at the same time, he was unwilling to refuse so pressing a request, Bassompierre, like a true courtier, came to his aid, and declared that, as he had “always preferred to deserve great honours than to possess them,” he was not so eager for the bâton as Schomberg, and would “without envy or regret” resign his claims in favour of one who was six years his senior, and one of his Majesty’s Ministers, and therefore entitled to the preference. “M. de Schomberg,” says he, “feeling that my courtesy had placed him under a great obligation, thanked me very gracefully; but the King persisted in refusing to promote one of us without the other; and so we withdrew.” On July 13, Louis XIII left Castelnaudary and proceeded, by way of Carcassonne and Narbonne, to Béziers, where he remained for some little time. Bassompierre, however, rejoined the army, which was advancing slowly towards Montpellier, and which, on August 2, laid siege simultaneously to the towns of Lunel and Marsillargues, situated about a league from one another. Marsillargues surrendered almost at once, and Lunel a few days later, the garrison of the latter place, by the terms of the capitulation, being permitted to march out with their swords only; their other weapons were to be placed in the carts which carried their baggage.
Bassompierre had received orders to enter the town with the Guards the moment the garrison evacuated it. On his way thither, he saw great numbers of disbanded soldiers of different regiments, landsknechts and Swiss as well as French, lingering about, and felt sure that their presence boded no good, and that they were meditating an attack upon the baggage. He accordingly decided not to allow the garrison to leave until he had ridden back to the Royal camp to warn Praslin, whom he advised to take measures to prevent any such attempt. But the marshal replied that “he was not a child, and that he understood his business, and that if he [Bassompierre] would only give the necessary orders within the town, he would do the same without.” Bassompierre returned to the town and directed the garrison to march out with their baggage, after which he entered with his troops, and gave orders that the gates should be closed and the breach which the besiegers’ cannon had made strongly guarded, as he thought it not improbable that an attempt might be made to enter and pillage the place.
“There was some degree of order in the departure of the enemy,” he says, “until the baggage came in sight; but, when that appeared, all the disbanded soldiers of our army rushed upon it, before it was possible for the marshal or Portes or Marillac to prevent them, and plundered these poor soldiers, 400 of whom they inhumanly butchered.” Bassompierre, however, had the satisfaction of executing rigorous justice upon some of these ruffians:— “Eight soldiers, of different countries and regiments, presented themselves at the gates of Lunel, with more than twenty prisoners, whom they brought tied together, with the intention of entering the town. Their swords were stained with the blood of those whom they had massacred, and they were so laden with booty that they could hardly walk. Finding the gate of Lunel shut, they called to the sentries to go and tell me to give orders for them to be let in. I went to the gate in consequence of what I heard, which I found to be true. I let them in and then ordered these eight fine fellows to be bound with the same cords with which they had bound the twenty prisoners. After giving these men the booty of the eight soldiers, whom, without any form of trial, I caused to be hanged before their eyes on a tree near the bridge of Lunel, I had them escorted by my carabiniers so far as the road to Cauvisson. On the morrow, Monsieur le Prince was very pleased with what I had done and thanked me.” Two or three days after the Royal troops had taken possession of Lunel, the town narrowly escaped being destroyed, with everyone within its walls. Bassompierre was at dinner with Créquy, Schomberg, and the Duc de Montmorency when there was a violent explosion, which partially wrecked the room in which they sat, though, happily, they were unhurt. They ran out to ascertain the cause, and learned that one of a train of ammunition- waggons which was entering the town had caught fire, and that the flames had reached the powder, with the result that several houses had been destroyed and others were blazing furiously. The utmost consternation prevailed, for the explosion had occurred near the gate by which the waggons had entered, and the débris of the houses barred the approach to it, while the other gates had been blocked up by Condé’s orders; and the fire was rapidly approaching a convent, in the vaults of which a great quantity
of powder was stored. If once it reached it, the whole town would be consumed, with all the troops and inhabitants. “The confusion was extreme,” says Bassompierre, “and, as everyone was thinking only of himself and his own safety, no one ran to extinguish the fire; all the people sought only to get out of the town, but no one could find a way. At length, I caused one of the blocked-up gates to be broken open, through which everyone could get out, and, having by this expedient got more elbow-room, we removed our powder to a safe place and extinguished the fire, by which more than fifty persons had perished.” The following day Bassompierre went with a body of 500 cavalry to Villeneuve-de-Maguelonne to escort the King to Lunel, where his Majesty arrived on August 15. On the 17th, Louis XIII went to visit Sommières, which had just surrendered to his troops, and on the return journey Schomberg, whose jealousy of Bassompierre was increasing daily, finding an opportunity for private conversation with his sovereign, did not fail to turn it to account: “On the road M. de Schomberg said to the King that I was his enemy, and he begged him to believe nothing that I might say about him. The King replied that he was entirely wrong, and that I had never spoken of him except to his advantage, nor of any other person, and that Schomberg knew me very little to take me for a man who did ill turns to people. He [Schomberg] was not a little astonished by this answer.” Perceiving by Bassompierre’s manner that the King had told him of their conversation, Schomberg requested Puisieux to effect a reconciliation between them, to which Bassompierre “consented reluctantly and after he had expressed to him his sentiments.” Schomberg would appear to have possessed an unusual amount of assurance, even for a German, for, immediately afterwards, he begged the man whom he had attempted to injure to employ his good offices with the King to obtain for him the governments which d’Épernon was about to resign in order to accept that of Guienne. This cool request, however, proved a little too much for Bassompierre, whose friend Praslin also aspired to these offices; and he replied that, not only should he refuse to speak in his favour, but should oppose him, until Praslin had been provided for. Eventually d’Épernon’s governments were divided between the two, Praslin
receiving Saintonge and Aulnis, and Schomberg the Angoumois and the Limousin. On August 27, Louis XIII arrived at Laverune, a little to the west of Montpellier, and on the following day Lesdiguières, who had been received into the Catholic Church in the Cathedral of Grenoble on the 24th, took the oath as Constable of France; after which, to the great mortification of Schomberg, the King informed Bassompierre that it was his intention to confer the vacant marshal’s bâton upon him, and that he would give orders for the necessary patent to be made out forthwith. His Majesty’s decision to give it to Bassompierre, notwithstanding what he had told him and Schomberg a fortnight before, was no doubt due to the fact that he had just bestowed a lucrative government upon the latter and considered that he ought to be content for the present with that proof of the royal favour. However, M. de Schomberg, who was one of those whose appetite for honours and emoluments seems only to have been stimulated by attempts to satisfy it, did not view the matter in that light, and felt deeply aggrieved.

Programming TypeScript Making your JavaScript applications scale Boris Cherny

  • 1.
    Programming TypeScript Makingyour JavaScript applications scale Boris Cherny install download https://ebookmeta.com/product/programming-typescript-making-your- javascript-applications-scale-boris-cherny/ Download more ebook from https://ebookmeta.com
  • 2.
  • 4.
    Praise for ProgrammingTypeScript This is the right book to help you learn TypeScript in depth. Programming TypeScript shows all the benefits of using a type system on top of JavaScript and provides deep insight into how to master the language. —Minko Gechev, Engineer, Angular Team at Google Programming TypeScript onboarded me to the TypeScript tooling and overall ecosystem quickly and efficiently. Every usage question I had was covered by concise, real-world examples. The “Advanced Types” chapter breaks down terminology I usually stumble over, and shows how to leverage TypeScript to create extremely safe code that’s still pleasant to use. —Sean Grove, Cofounder of OneGraph Boris has provided a comprehensive guide to TypeScript. Read this for the 10,000-foot view all the way back down to Earth, and then some. —Blake Embrey, Engineer at Opendoor, author of TypeScript Node and Typings
  • 6.
    Boris Cherny Programming TypeScript MakingYour JavaScript Applications Scale Boston Farnham Sebastopol Tokyo Beijing Boston Farnham Sebastopol Tokyo Beijing
  • 7.
    978-1-492-03765-1 [LSI] 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/institu‐ tional sales department: 800-998-9938 or corporate@oreilly.com. Development Editor: Angela Rufino Indexer: Ellen 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 2019-08-09: Second 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.
  • 8.
    To Sasha andMichael, who might also fall in love with types, someday.
  • 10.
    Table of Contents Preface.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2. TypeScript: A 10_000 Foot View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 The Compiler 5 The Type System 7 TypeScript Versus JavaScript 8 Code Editor Setup 11 tsconfig.json 11 tslint.json 13 index.ts 13 Exercises 15 3. All About Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Talking About Types 18 The ABCs of Types 19 any 19 unknown 20 boolean 21 number 22 bigint 23 string 23 symbol 24 Objects 25 Intermission: Type Aliases, Unions, and Intersections 30 Arrays 33 vii
  • 11.
    Tuples 35 null, undefined,void, and never 37 Enums 39 Summary 43 Exercises 44 4. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Declaring and Invoking Functions 45 Optional and Default Parameters 47 Rest Parameters 48 call, apply, and bind 50 Typing this 50 Generator Functions 52 Iterators 53 Call Signatures 55 Contextual Typing 58 Overloaded Function Types 58 Polymorphism 64 When Are Generics Bound? 68 Where Can You Declare Generics? 69 Generic Type Inference 71 Generic Type Aliases 73 Bounded Polymorphism 74 Generic Type Defaults 78 Type-Driven Development 79 Summary 80 Exercises 81 5. Classes and Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Classes and Inheritance 83 super 89 Using this as a Return Type 89 Interfaces 91 Declaration Merging 93 Implementations 94 Implementing Interfaces Versus Extending Abstract Classes 96 Classes Are Structurally Typed 97 Classes Declare Both Values and Types 98 Polymorphism 100 Mixins 101 Decorators 104 viii | Table of Contents
  • 12.
    Simulating final Classes107 Design Patterns 107 Factory Pattern 108 Builder Pattern 109 Summary 110 Exercises 110 6. Advanced Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Relationships Between Types 114 Subtypes and Supertypes 114 Variance 115 Assignability 121 Type Widening 122 Refinement 126 Totality 130 Advanced Object Types 132 Type Operators for Object Types 132 The Record Type 137 Mapped Types 137 Companion Object Pattern 140 Advanced Function Types 141 Improving Type Inference for Tuples 141 User-Defined Type Guards 142 Conditional Types 143 Distributive Conditionals 144 The infer Keyword 145 Built-in Conditional Types 146 Escape Hatches 147 Type Assertions 148 Nonnull Assertions 149 Definite Assignment Assertions 151 Simulating Nominal Types 152 Safely Extending the Prototype 154 Summary 156 Exercises 157 7. Handling Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Returning null 160 Throwing Exceptions 161 Returning Exceptions 163 The Option Type 165 Table of Contents | ix
  • 13.
    Summary 171 Exercises 172 8.Asynchronous Programming, Concurrency, and Parallelism. . . . . . . . . . . . . . . . . . . . . . 173 JavaScript’s Event Loop 174 Working with Callbacks 176 Regaining Sanity with Promises 178 async and await 183 Async Streams 184 Event Emitters 184 Typesafe Multithreading 187 In the Browser: With Web Workers 187 In NodeJS: With Child Processes 196 Summary 197 Exercises 198 9. Frontend and Backend Frameworks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Frontend Frameworks 199 React 201 Angular 207 Typesafe APIs 210 Backend Frameworks 212 Summary 213 10. Namespaces.Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 A Brief History of JavaScript Modules 216 import, export 218 Dynamic Imports 219 Using CommonJS and AMD Code 221 Module Mode Versus Script Mode 222 Namespaces 222 Collisions 225 Compiled Output 225 Declaration Merging 226 Summary 228 Exercise 228 11. Interoperating with JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Type Declarations 230 Ambient Variable Declarations 233 Ambient Type Declarations 234 x | Table of Contents
  • 14.
    Ambient Module Declarations235 Gradually Migrating from JavaScript to TypeScript 236 Step 1: Add TSC 237 Step 2a: Enable Typechecking for JavaScript (Optional) 238 Step 2b: Add JSDoc Annotations (Optional) 239 Step 3: Rename Your Files to .ts 240 Step 4: Make It strict 241 Type Lookup for JavaScript 242 Using Third-Party JavaScript 244 JavaScript That Comes with Type Declarations 245 JavaScript That Has Type Declarations on DefinitelyTyped 245 JavaScript That Doesn’t Have Type Declarations on DefinitelyTyped 246 Summary 247 12. Building and Running TypeScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Building Your TypeScript Project 249 Project Layout 249 Artifacts 250 Dialing In Your Compile Target 251 Enabling Source Maps 255 Project References 255 Error Monitoring 258 Running TypeScript on the Server 258 Running TypeScript in the Browser 259 Publishing Your TypeScript Code to NPM 261 Triple-Slash Directives 262 The types Directive 262 The amd-module Directive 264 Summary 265 13. Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 A. Type Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 B. Type Utilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 C. Scoped Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 D. Recipes for Writing Declaration Files for Third-Party JavaScript Modules. . . . . . . . . . . 275 E. Triple-Slash Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Table of Contents | xi
  • 15.
    F. TSC CompilerFlags for Safety. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 G. TSX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 xii | Table of Contents
  • 16.
    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, docu‐ ment 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 intu‐ itive, 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 con‐ cisely and precisely, letting you write applications in a way that’s fun, modern, and safe. Preface | xiii
  • 17.
    How This BookIs Organized This book has two aims: to give you a deep understanding of how the TypeScript lan‐ guage 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 top‐ ics 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 ver‐ sion is usually just called “esnext”). This will keep your code in line with the lat‐ est 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. xiv | Preface
  • 18.
    1 If you’renot coming from JavaScript, here’s an example: if you have an object o, and you want to add a prop‐ erty 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}. • You should keep your data structures immutable with spreads (...) most of the time.1 • You should make sure everything has a type, inferred when possible. Be careful not to abuse explicit types; 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 “Polymor‐ phism” on page 64) 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 func‐ tions. 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 leg‐ acy 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 ele‐ ments such as variable or function names, data types, environment variables, statements, and keywords. Preface | xv
  • 19.
    Constant width italic Showstext that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. 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 signifi‐ cant 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. xvi | Preface
  • 20.
    O’Reilly Online Learning Foralmost 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help compa‐ nies 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 bookques‐ tions@oreilly.com. For more information about our books, courses, conferences, and news, see our web‐ site 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 Preface | xvii
  • 21.
    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’Reilly 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” on page 210, and to Shyam Seshadri for his contri‐ bution in “Angular” on page 207. 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. xviii | Preface
  • 22.
    1 Depending onwhich 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. 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 Inter‐ net of Things (IoT) devices. It will make your programs safer by checking for com‐ mon 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.1 1
  • 23.
    Here are afew 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 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 obvi‐ ously 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 add a number and an array? let obj = {} obj.foo // Error: You forgot to define the property "foo" on obj. function a(b) { return b/2 } a("z") // Error: The function "a" expects a number, // but you gave it a string. Don’t get me wrong: trying to fix our mistakes for us is a neat feature for a program‐ ming language to have (if only it worked for more than just programs!). But for Java‐ Script, 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? 2 | Chapter 1: Introduction
  • 24.
    2 If you’renot sure what “type level” means here, don’t worry. We’ll go over it in depth in later chapters. 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 '+' cannot be applied to types '3' // and 'never[]'. let obj = {} obj.foo // Error TS2339: Property 'foo' does not exist on type '{}'. function a(b: number) { return b / 2 } a("z") // Error TS2345: Argument of type '"z"' is not assignable to // 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;2 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! Introduction | 3
  • 26.
    CHAPTER 2 TypeScript: A10_000 Foot View Over the next few chapters, I’ll introduce the TypeScript language, give you an over‐ view of how the TypeScript Compiler (TSC) works, and take you on a tour of Type‐ Script’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 trans‐ forms 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. 5
  • 27.
    3. Bytecode isevaluated by the runtime. Where TypeScript is special is that instead of compiling straight to bytecode, Type‐ Script compiles to… JavaScript code! You then run that JavaScript code like you nor‐ mally 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. JavaScript compilers and runtimes tend to be smushed into a single program called an engine; as a programmer, this is what you’ll nor‐ mally 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. 6 | Chapter 2: TypeScript: A 10_000 Foot View
  • 28.
    1 There arelanguages all over this spectrum: JavaScript, Python, and Ruby infer types at runtime; Haskell and OCaml infer and check missing types at compile time; Scala and TypeScript require some explicit types and infer and check the rest at compile time; and Java and C need explicit annotations for almost everything, which they check at compile time. In this process, steps 1–2 use your program’s types; step 3 does not. That’s worth reit‐ erating: 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 gener‐ ated 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 break‐ ing 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.1 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 booleans 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 let c = [true, false] // c is an array of booleans 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 The Type System | 7
  • 29.
    annotations only whennecessary, and let TypeScript work its inference magic for us whenever possible. 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 Java‐ Script’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 pro‐ gram 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 Java‐ Script to typed TypeScript (more on that in “Gradually Migrating from JavaScript to TypeScript” on page 236), 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 8 | Chapter 2: TypeScript: A 10_000 Foot View
  • 30.
    what you reallymeant 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, Type‐ Script complains as soon as you do something invalid. When you run that same Java‐ Script code through TSC, you’ll get an error: 3 + [1]; // Error TS2365: Operator '+' cannot be applied to // types '3' and 'number[]'. (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 The Type System | 9
  • 31.
    2 To besure, JavaScript surfaces syntax errors and a few select bugs (like multiple const declarations with the same name in the same scope) after it parses your program, but before it runs it. If you parse your JavaScript as part of your build process (e.g., with Babel), you can surface these errors at build time. 3 Incrementally compiled languages can be quickly recompiled when you make a small change, rather than having to recompile your whole program (including the parts you didn’t touch). 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.2 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 an amazing experience if you’ve never worked with an incrementally compiled statically typed language before.3 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. 10 | Chapter 2: TypeScript: A 10_000 Foot View
  • 32.
    4 This putsTSC in the mystical class of compilers known as self-hosting compilers, or compilers that compile themselves. 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 Sub‐ lime 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,4 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. 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 NodeJS 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. Code Editor Setup | 11
  • 33.
    5 For thisexercise, we’re creating a tsconfig.json manually. When you set up TypeScript projects in the future, you can use TSC’s built-in initialize command to generate one for you: ./node_modules/.bin/tsc --init. Create a new file called tsconfig.json in your root folder (touch tsconfig.json),5 then pop it open in your code editor and give it the following contents: { "compilerOptions": { "lib": ["es2015"], "module": "commonjs", "outDir": "dist", "sourceMap": true, "strict": true, "target": "es2015" }, "include": [ "src" ] } Let’s briefly go over some of those options and what they mean (Table 2-2): Table 2-2. tsconfig.json options Option Description include Which folders should TSC look in to find your TypeScript files? lib Which APIs should TSC assume exist in the environment you’ll be running your code in? This includes things like ES5’s Function.prototype.bind, ES2015’s Object.assign, and the DOM’s document.querySelector. module Which module system should TSC compile your code to (CommonJS, SystemJS, ES2015, etc.)? outDir Which folder should TSC put your generated JavaScript code in? strict Be as strict as possible when checking for invalid code. This option enforces that all of your code is properly typed. We’ll be using it for all of the examples in the book, and you should use it for your TypeScript project too. target Which JavaScript version should TSC compile your code to (ES3, ES5, ES2015, ES2016, etc.)? These are just a few of the available options—tsconfig.json supports dozens of options, and new ones are added all the time. You won’t find yourself changing these much in practice, besides dialing in the module and target settings when switching to a new module bundler, adding "dom" to lib when writing TypeScript for the browser (you’ll learn more about this in Chapter 12), or adjusting your level of strictness when migrating your existing JavaScript code to TypeScript (see “Gradu‐ ally Migrating from JavaScript to TypeScript” on page 236). For a complete and up-to- date list of supported options, head over to the official documentation on the TypeScript website. 12 | Chapter 2: TypeScript: A 10_000 Foot View
  • 34.
    Note that whileusing a tsconfig.json file to configure TSC is handy because it lets us check that configuration into source control, you can set most of TSC’s options from the command line too. Run ./node_modules/.bin/tsc --help for a list of available command-line options. tslint.json Your project should also have a tslint.json file containing your TSLint configuration, codifying whatever stylistic conventions you want for your code (tabs versus spaces, etc.). Using TSLint is optional, but it’s strongly recommend for all Type‐ Script projects to enforce a consistent coding style. Most impor‐ tantly, it will save you from arguing over code style with coworkers during code reviews. The following command will generate a tslint.json file with a default TSLint configuration: ./node_modules/.bin/tslint --init You can then add overrides to this to conform with your own coding style. For exam‐ ple, my tslint.json looks like this: { "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "rules": { "semicolon": false, "trailing-comma": false } } For the full list of available rules, head over to the TSLint documentation. You can also add custom rules, or install extra presets (like for ReactJS). index.ts Now that you’ve set up your tsconfig.json and tslint.json, create a src folder containing your first TypeScript file: mkdir src touch src/index.ts index.ts | 13
  • 35.
    Your project’s folderstructure should now look this: chapter-2/ ├──node_modules/ ├──src/ │ └──index.ts ├──package.json ├──tsconfig.json └──tslint.json Pop open src/index.ts in your code editor, and enter the following TypeScript code: console.log('Hello TypeScript!') Then, compile and run your TypeScript code: # Compile your TypeScript with TSC ./node_modules/.bin/tsc # Run your code with NodeJS node ./dist/index.js If you’ve followed all the steps here, your code should run and you should see a single log in your console: Hello TypeScript! That’s it—you just set up and ran your first TypeScript project from scratch. Nice work! Since this might have been your first time setting up a TypeScript project from scratch, I wanted to walk through each step so you have a sense for all the moving pieces. There are a couple of short‐ cuts you can take to do this faster next time: • Install ts-node, and use it to compile and run your TypeScript with a single command. • Use a scaffolding tool like typescript-node-starter to quickly generate your folder structure for you. 14 | Chapter 2: TypeScript: A 10_000 Foot View
  • 36.
    Exercises Now that yourenvironment is set up, open up src/index.ts in your code editor. Enter the following code: let a = 1 + 2 let b = a + 3 let c = { apple: a, banana: b } let d = c.apple * 4 Now hover over a, b, c, and d, and notice how TypeScript infers the types of all your variables for you: a is a number, b is a number, c is an object with a specific shape, and d is also a number (Figure 2-3). Figure 2-3. TypeScript inferring types for you Play around with your code a bit. See if you can: • Get TypeScript to show a red squiggly when you do something invalid (we call this “throwing a TypeError“). • Read the TypeError, and try to understand what it means. • Fix the TypeError and see the red squiggly disappear. If you’re ambitious, try to write a piece of code that TypeScript is unable to infer the type for. Exercises | 15
  • 38.
    CHAPTER 3 All AboutTypes In the last chapter I introduced the idea of type systems, but I never defined what the type in type system really means. Type A set of values and the things you can do with them. If that sounds confusing, let me give a few familiar examples: • The boolean type is the set of all booleans (there are just two: true and false) and the operations you can perform on them (like ||, &&, and !). • The number type is the set of all numbers and the operations you can perform on them (like +, -, *, /, %, ||, &&, and ?), including the methods you can call on them like .toFixed, .toPrecision, .toString, and so on. • The string type is the set of all strings and the operations you can perform on them (like +, ||, and &&), including the methods you can call on them like .concat and .toUpperCase. When you see that something is of type T, not only do you know that it’s a T, but you also know exactly what you can do with that T (and what you can’t). Remember, the whole point is to use the typechecker to stop you from doing invalid things. And the way the typechecker knows what’s valid and what’s not is by looking at the types you’re using and how you’re using them. In this chapter we’ll take a tour of the types available in TypeScript and cover the basics of what you can do with each of them. Figure 3-1 gives an overview. 17
  • 39.
    Figure 3-1. TypeScript’stype hierarchy Talking About Types When programmers talk about types, they share a precise, common vocabulary to describe what they mean. We’re going to use this vocabulary throughout this book. Say you have a function that takes some value and returns that value multiplied by itself: function squareOf(n) { return n * n } squareOf(2) // evaluates to 4 squareOf('z') // evaluates to NaN Clearly, this function will only work for numbers—if you pass anything besides a number to squareOf, the result will be invalid. So what we do is explicitly annotate the parameter’s type: function squareOf(n: number) { return n * n } squareOf(2) // evaluates to 4 squareOf('z') // Error TS2345: Argument of type '"z"' is not assignable to // parameter of type 'number'. Now if we call squareOf with anything but a number, TypeScript will know to com‐ plain right away. This is a trivial example (we’ll talk a lot more about functions in the next chapter), but it’s enough to introduce a couple of concepts that are key to talking 18 | Chapter 3: All About Types
  • 40.
    about types inTypeScript. We can say the following things about the last code exam‐ ple: 1. squareOf’s parameter n is constrained to number. 2. The type of the value 2 is assignable to (equivalently: compatible with) number. Without a type annotation, squareOf is unconstrained in its parameter, and you can pass any type of argument to it. Once we constrain it, TypeScript goes to work for us verifying that every place we call our function, we call it with a compatible argument. In this example the type of 2 is number, which is assignable to squareOf’s annotation number, so TypeScript accepts our code; but 'z' is a string, which is not assignable to number, so TypeScript complains. You can also think of it in terms of bounds: we told TypeScript that n’s upper bound is number, so any value we pass to squareOf has to be at most a number. If it’s anything more than a number (like, if it’s a value that might be a number or might be a string), then it’s not assignable to n. I’ll define assignability, bounds, and constraints more formally in Chapter 6. For now, all you need to know is this is the language that we use to talk about whether or not a type can be used in a place where we require a certain type. The ABCs of Types Let’s take a tour of the types TypeScript supports, what values they contain, and what you can do with them. We’ll also cover a few basic language features for working with types: type aliases, union types, and intersection types. any any is the Godfather of types. It does anything for a price, but you don’t want to ask any for a favor unless you’re completely out of options. In TypeScript everything needs to have a type at compile time, and any is the default type when you (the pro‐ grammer) and TypeScript (the typechecker) can’t figure out what type something is. It’s a last resort type, and you should avoid it when possible. Why should you avoid it? Remember what a type is? (It’s a set of values and the things you can do with them.) any is the set of all values, and you can do anything with any. That means that if you have a value of type any you can add to it, multiply by it, call .pizza() on it—anything. any makes your value behave like it would in regular JavaScript, and totally prevents the typechecker from working its magic. When you allow any into your code you’re flying blind. Avoid any like fire, and use it only as a very, very last resort. The ABCs of Types | 19
  • 41.
    On the rareoccasion that you do need to use it, you do it like this: let a: any = 666 // any let b: any = ['danger'] // any let c = a + b // any Notice how the third type should report an error (why are you trying to add a num‐ ber and an array?), but doesn’t because you told TypeScript that you’re adding two anys. If you want to use any, you have to be explicit about it. When TypeScript infers that some value is of type any (for example, if you forgot to annotate a function’s parameter, or if you imported an untyped JavaScript module), it will throw a compile-time exception and toss a red squiggly at you in your editor. By explicitly annotating a and b with the any type (: any), you avoid the exception—it’s your way of telling TypeScript that you know what you’re doing. TSC Flag: noImplicitAny By default, TypeScript is permissive, and won’t complain about values that it infers as any. To get TypeScript to complain about implicit anys, be sure to enable the noImplicitAny flag in your tsconfig.json. noImplicitAny is part of the strict family of TSC flags, so if you already enabled strict in your tsconfig.json (as we did in “tscon‐ fig.json” on page 11), you’re good to go. unknown If any is the Godfather, then unknown is Keanu Reeves as undercover FBI agent Johnny Utah in Point Break: laid back, fits right in with the bad guys, but deep down has a respect for the law and is on the side of the good guys. For the few cases where you have a value whose type you really don’t know ahead of time, don’t use any, and instead reach for unknown. Like any, it represents any value, but TypeScript won’t let you use an unknown type until you refine it by checking what it is (see “Refinement” on page 126). What operations does unknown support? You can compare unknown values (with ==, ===, ||, &&, and ?), negate them (with !), and refine them (like you can any other type) with JavaScript’s typeof and instanceof operators. Use unknown like this: let a: unknown = 30 // unknown let b = a === 123 // boolean let c = a + 10 // Error TS2571: Object is of type 'unknown'. if (typeof a === 'number') { let d = a + 10 // number } 20 | Chapter 3: All About Types
  • 42.
    1 Almost. Whenunknown is part of a union type, the result of the union will be unknown. You’ll read more about union types in “Union and intersection types” on page 32. This example should give you a rough idea of how to use unknown: 1. TypeScript will never infer something as unknown—you have to explicitly anno‐ tate it (a).1 2. You can compare values to values that are of type unknown (b). 3. But, you can’t do things that assume an unknown value is of a specific type (c); you have to prove to TypeScript that the value really is of that type first (d). boolean The boolean type has two values: true and false. You can compare them (with ==, ===, ||, &&, and ?), negate them (with !), and not much else. Use boolean like this: let a = true // boolean var b = false // boolean const c = true // true let d: boolean = true // boolean let e: true = true // true let f: true = false // Error TS2322: Type 'false' is not assignable // to type 'true'. This example shows a few ways to tell TypeScript that something is a boolean: 1. You can let TypeScript infer that your value is a boolean (a and b). 2. You can let TypeScript infer that your value is a specific boolean (c). 3. You can tell TypeScript explicitly that your value is a boolean (d). 4. You can tell TypeScript explicitly that your value is a specific boolean (e and f). In general, you will use the first or second way in your programs. Very rarely, you’ll use the fourth way—only when it buys you extra type safety (I’ll show you examples of that throughout this book). You will almost never use the third way. The second and fourth cases are particularly interesting because while they do some‐ thing intuitive, they’re supported by surprisingly few programming languages and so might be new to you. What I did in that example was say, “Hey TypeScript! See this variable e here? e isn’t just any old boolean—it’s the specific boolean true.” By using a value as a type, I essentially limited the possible values for e and f from all booleans to one specific boolean each. This feature is called type literals. The ABCs of Types | 21
  • 43.
    2 At thetime of writing, you can’t use NaN, Infinity, or -Infinity as type literals. Type literal A type that represents a single value and nothing else. In the fourth case I explicitly annotated my variables with type literals, and in the sec‐ ond case TypeScript inferred a literal type for me because I used const instead of let or var. Because TypeScript knows that once a primitive is assigned with const its value will never change, it infers the most narrow type it can for that variable. That’s why in the second case TypeScript inferred c’s type as true instead of as boolean. To learn more about why TypeScript infers different types for let and const, jump ahead to “Type Widening” on page 122. We will revisit type literals throughout this book. They are a powerful language fea‐ ture that lets you squeeze out extra safety all over the place. Type literals make Type‐ Script unique in the language world and are something you should lord over your Java friends. number number is the set of all numbers: integers, floats, positives, negatives, Infinity, NaN, and so on. Numbers can do, well, numbery things, like addition (+), subtraction (-), modulo (%), and comparison (<). Let’s look at a few examples: let a = 1234 // number var b = Infinity * 0.10 // number const c = 5678 // 5678 let d = a < b // boolean let e: number = 100 // number let f: 26.218 = 26.218 // 26.218 let g: 26.218 = 10 // Error TS2322: Type '10' is not assignable // to type '26.218'. Like in the boolean example, there are four ways to type something as a number: 1. You can let TypeScript infer that your value is a number (a and b). 2. You can use const so TypeScript infers that your value is a specific number (c).2 3. You can tell TypeScript explicitly that your value is a number (e). 4. You can tell TypeScript explicitly that your value is a specific number (f and g). And just like with booleans, you’re usually going to let TypeScript infer the type for you (the first way). Once in a while you’ll do some clever programming that requires 22 | Chapter 3: All About Types
  • 44.
    your number’s typeto be restricted to a specific value (the second or fourth way). There is no good reason to explicitly type something as a number (the third way). When working with long numbers, use numeric separators to make those numbers easier to read. You can use numeric separa‐ tors in both type and value positions: let oneMillion = 1_000_000 // Equivalent to 1000000 let twoMillion: 2_000_000 = 2_000_000 bigint bigint is a newcomer to JavaScript and TypeScript: it lets you work with large inte‐ gers without running into rounding errors. While the number type can only represent whole numbers up to 253 , bigint can represent integers bigger than that too. The bigint type is the set of all BigInts, and supports things like addition (+), subtraction (-), multiplication (*), division (/), and comparison (<). Use it like this: let a = 1234n // bigint const b = 5678n // 5678n var c = a + b // bigint let d = a < 1235 // boolean let e = 88.5n // Error TS1353: A bigint literal must be an integer. let f: bigint = 100n // bigint let g: 100n = 100n // 100n let h: bigint = 100 // Error TS2322: Type '100' is not assignable // to type 'bigint'. Like with boolean and number, there are four ways to declare bigints. Try to let Type‐ Script infer your bigint’s type when you can. At the time of writing, bigint is not yet natively supported by every JavaScript engine. If your application relies on bigint, be careful to check whether or not it’s supported by your target plat‐ form. string string is the set of all strings and the things you can do with them like concatenate (+), slice (.slice), and so on. Let’s see some examples: let a = 'hello' // string var b = 'billy' // string const c = '!' // '!' let d = a + ' ' + b + c // string let e: string = 'zoom' // string let f: 'john' = 'john' // 'john' The ABCs of Types | 23
  • 45.
    let g: 'john'= 'zoe' // Error TS2322: Type "zoe" is not assignable // to type "john". Like boolean and number, there are four ways to declare string types, and you should let TypeScript infer the type for you whenever you can. symbol symbol is a relatively new language feature that arrived with one of the latest major JavaScript revisions (ES2015). Symbols don’t come up often in practice; they are used as an alternative to string keys in objects and maps, in places where you want to be extra sure that people are using the right well-known key and didn’t accidentally set the key—think setting a default iterator for your object (Symbol.iterator), or over‐ riding at runtime whether or not your object is an instance of something (Sym bol.hasInstance). Symbols have the type symbol, and there isn’t all that much you can do with them: let a = Symbol('a') // symbol let b: symbol = Symbol('b') // symbol var c = a === b // boolean let d = a + 'x' // Error TS2469: The '+' operator cannot be applied // to type 'symbol'. The way Symbol('a') works in JavaScript is by creating a new symbol with the given name; that symbol is unique, and will not be equal (when compared with == or ===) to any other symbol (even if you create a second symbol with the same exact name!). Similarly to how the value 27 is inferred to be a number when declared with let but the specific number 27 when you declare it with const, symbols are inferred to be of type symbol but can be explicitly typed as unique symbol: const e = Symbol('e') // typeof e const f: unique symbol = Symbol('f') // typeof f let g: unique symbol = Symbol('f') // Error TS1332: A variable whose type is a // 'unique symbol' type must be 'const'. let h = e === e // boolean let i = e === f // Error TS2367: This condition will always return // 'false' since the types 'unique symbol' and // 'unique symbol' have no overlap. This example shows off a few ways to create unique symbols: 1. When you declare a new symbol and assign it to a const variable (not a let or var variable), TypeScript will infer its type as unique symbol. It will show up as typeof yourVariableName, not unique symbol, in your code editor. 2. You can explicitly annotate a const variable’s type as unique symbol. 3. A unique symbol is always equal to itself. 24 | Chapter 3: All About Types
  • 46.
    4. TypeScript knowsat compile time that a unique symbol will never be equal to any other unique symbol. Think of unique symbols like other literal types, like 1, true, or "literal". They’re a way to create a type that represents a particular inhabitant of symbol. Objects TypeScript’s object types specify the shapes of objects. Notably, they can’t tell the dif‐ ference between simple objects (like the kind you make with {}) and more compli‐ cated ones (the kind you create with new Blah). This is by design: JavaScript is generally structurally typed, so TypeScript favors that style of programming over a nominally typed style. Structural typing A style of programming where you just care that an object has certain properties, and not what its name is (nominal typing). Also called duck typing in some languages (or, not judging a book by its cover). There are a few ways to use types to describe objects in TypeScript. The first is to declare a value as an object: let a: object = { b: 'x' } What happens when you access b? a.b // Error TS2339: Property 'b' does not exist on type 'object'. Wait, that’s not very useful! What’s the point of typing something as an object if you can’t do anything with it? Why, that’s a great point, aspiring TypeScripter! In fact, object is a little narrower than any, but not by much. object doesn’t tell you a lot about the value it describes, just that the value is a JavaScript object (and that it’s not null). What if we leave off the explicit annotation, and let TypeScript do its thing? let a = { b: 'x' } // {b: string} a.b // string let b = { c: { The ABCs of Types | 25
  • 47.
    Another Random ScribdDocument with Unrelated Content
  • 48.
    took more pleasurethan in that of any of them, and whom, they knew, the late Constable had regarded as his only dangerous rival. It is certain that, had Bassompierre been so minded, he would have stood an excellent chance of succeeding to Luynes’s place as favourite, and that his elevation would have been well received, as he was exceedingly popular both at the Court and in the Army. But his epicurean wisdom rejected the idea of a life of gilded slavery; to be obliged to forgo the society of his “beautiful mistresses,” in order to dance attendance upon his youthful sovereign and make up his mind for him a dozen times a day, was not at all an attractive prospect to one who infinitely preferred pleasure to grandeur; the royal favour, without the responsibilities of power, was sufficient for him. The Cardinal de Retz, Schomberg and Puisieux had the advantage of being near the King at the time of the Constable’s death. The first two at once joined forces against Puisieux and “aspired to become all-powerful and to restrain the King from doing anything except on their advice.” They secured a decided success by persuading Louis XIII to bestow the vacant office of Keeper of the Seals upon De Vic, a counsellor of State, who was devoted to their interests, and then put their heads together to find a means of separating the King from Bassompierre, whom they regarded as a serious obstacle in the path of their ambition. Louis XIII arrived at Bordeaux on December 21, and shortly afterwards the two Ministers proposed to him to leave Bassompierre in Guienne as lieutenant-general of that province, in place of the Maréchal de Roquelaure, who was to be compensated for the loss of his post by a present of 200,000 livres and the government of Lectoure. Having obtained his Majesty’s consent to this arrangement, they sent Roucellaï to sound Bassompierre on the matter and “even offered to add to this charge that of marshal of France.” But Bassompierre preferred to wait upon events and to see into whose hands the management of affairs would fall, foreseeing that whoever might secure it would not be strong enough to maintain his position without support, and “being assured that he would be very pleased to have him for a friend, and to give him a larger share of the cake than they [Retz and Schomberg] were offering him.” “When the King spoke to me of the lieutenancy-general [of Guienne], I answered that I should esteem myself more happy to occupy the post of Colonel-General of the Swiss near his person than any other away from it;
  • 49.
    that I wasonly just recovering from a severe illness which demanded three months’ repose, and that during that time I desired no other employment than that of my first office of Colonel-General. And to this his Majesty agreed.” Although foiled in this attempt to get Bassompierre out of the way, Retz and Schomberg presently returned to the charge, and having persuaded the Maréchal de Thémines to surrender the government of Béarn, in exchange for the lieutenancy-general of Guienne, offered it to Bassompierre. The government of Béarn, though, in the present circumstances, it could scarcely be regarded as a bed of roses, was a very honourable and lucrative post. But its acceptance would, of course, entail an almost complete separation from the King, and from—what was more important in Bassompierre’s estimation—the Court and Paris; and he therefore returned the same answer as he had in the case of Guienne. A day or two later, Bassompierre had the satisfaction of inflicting a sharp reverse upon the two Ministers. The Cardinal and Schomberg had urged the King to follow up the capture of Monheurt by the surprise of Castillon, on the Dordogne, which, they declared, could very easily be carried out and would have an excellent effect. Now, Castillon belonged to the Duc de Bouillon, who, at the outbreak of hostilities, had entered into a compact with Louis XIII, which stipulated that this and other towns within his jurisdiction should “remain in the service of the King, but without making war on those of the Religion”; while the King, on his side, promised that they should in no way be interfered with. To seize Castillon therefore would be a direct breach of this agreement, and could only be defended on the ground that the townsfolk had sent assistance to the Huguenots, of which there was no evidence of any value. Nevertheless, Louis XIII allowed himself to be persuaded by the two Ministers to consent to this being done, provided that the rest of the Council did not oppose it. When, however, the project was laid before the Council, Bassompierre rose and denounced it in a vigorous speech, in which he declared that, if executed, it would be a “great stain on the King’s honour and reputation,” after which he proceeded to give his Majesty some very wholesome advice on the danger of breaking his royal word. “Sire,” said he, “it is easy for a man to deceive a person who trusts him, but it is not easy to deceive a second time. A promise badly observed only
  • 50.
    once deprives himwho breaks it of the trust of the whole world.” And he stigmatized the counsel which had been given the King, of the source of which he pretended ignorance, as “interested, evil-intentioned and rash,” which, if followed, would probably result in driving Bouillon into rebellion, and with him numbers of Protestants who had hitherto remained neutral, since they would feel that it was impossible to trust the word of the King. One or two other members of the Council signified their agreement with the views expressed by Bassompierre, upon which the King announced that he had come to the same conclusion, to the great discomfiture of Retz and Schomberg, who were forced to recognise that their design of governing the young monarch was likely to prove a much more difficult task than they had bargained for. Louis XIII left Bordeaux on the last day of the year, and travelled by easy stages towards Paris. At Château-neuf-sur-Charente, where he arrived on January 6, 1622, another pretender to Luynes’s shoes appeared upon the scene, in the person of Condé. “Monsieur le Prince,” says Bassompierre, “who was extremely cunning and supple, was equally courteous to everyone, without inclining to any side, until he had perceived the tendency of the market. His design was to persuade the King to continue the Huguenot war, for three reasons, in my opinion: first, because of the ardent affection which he had for his religion and his hatred against the Huguenot party; secondly, because he thought that he could govern the King better in time of war than in time of peace, since he would undoubtedly be lieutenant-general of his army; and, lastly, in order to separate him from the Queen his mother, the Chancellor and the old Ministers, who were his antipathy.” In order to ascertain the state of the Court, Condé addressed himself to the Abbé Roucellaï, an adroit and insinuating personage, who had been in turn the protégé of Concini, the Queen-Mother and Luynes, and who, now that the Constable was dead, had decided to seek a new patron in Monsieur le Prince. The abbé told him that there were two parties at the Court. On one side, were the three Ministers, Retz, Schomberg and the new Keeper of the Seals, De Vic, “who desired to possess the King’s mind to the exclusion of everyone else”; on the other, the three marshals of France, Praslin,
  • 51.
    Chaulnes, and Créquy[2]and some others, who were resolved not to submit to this. He added that the King conversed frequently with Bassompierre and appeared to have a rather high opinion of him, and that, if the latter had any ambition to succeed to the favour of the late Constable, it might very well be realised. That, however, did not seem to be his desire, “although he was disposed to accept the share in the King’s good graces which his services might merit.” Bassompierre and the Ministers, he told the prince, were “not always of the same opinion,” and only a few days before he had spoken very bitterly against them before his Majesty in a council. Condé then inquired if Bassompierre were in favour of continuing the war against the Huguenots, and Roucellaï answered that he had pressed Luynes to enter into negotiations with Rohan, from fear that the Royal army would be obliged to raise the siege of Montauban. As a result of this conversation, the prince sent Roucellaï to Bassompierre to inform him that he wished to speak to him and ascertain his views in regard to the war. Before seeing Bassompierre, however, Condé had an interview with the Ministers, whom he found in warlike mood, not because they believed that any useful purpose could be served by a continuance of this fratricidal strife, but for the same selfish reasons as he himself desired it, namely, “to keep the King so far as possible from Paris, in order the better to govern him.” He then approached Créquy, who answered that he was in favour of peace, provided that it could be obtained on advantageous and honourable terms. Bassompierre gave him a similar reply, when he spoke to him on the matter, and added that he would find Praslin and all other good servants of the King of the same opinion. “It is singular,” said the prince; “all you men of war, who ought to desire it, and can only make your way by means of it, want peace; and the lawyers and statesmen demand war.” “I answered,” says Bassompierre, “that I desired war, and that it ought to bring me fortune and advancement, but only on condition that it was for the service of the King and the good of the State; and that otherwise I should esteem myself a bad servant of the King and a bad Frenchman, if, for my own private advantage, I were to desire a thing which must cause both so much evil and prejudice.” After this sharp, if indirect, rebuke, Condé left him and told Roucellaï that, after sounding Créquy and Bassompierre, he found that he was likely to have more in common with the Ministers than with them.
  • 52.
    During the remainderof the journey to Paris, skirmishes between the rival parties were of frequent occurrence, each doing everything possible to prejudice the King against the other. At Sauzé, where the Court arrived on the 10th, Bassompierre again scored at the expense of the Ministers. Louis XIII was about to sit down to cards with Bassompierre and Praslin, when the three Ministers were announced. “The King said to us as he saw them enter: ‘Mon Dieu, how tiresome these people are! When one is thinking of amusing oneself, they come to torment me, and most often they have nothing to tell me.’ I, who was very pleased to have the chance of giving them a rebuff in revenge for the ill turns they were doing me every day, said to the King: ‘What, Sire! Do these gentlemen come without being sent for by you, or without having first informed your Majesty that there is something of importance to deliberate upon, and then ask for your time?’ ‘No,’ said he, ‘they never inform me, and come when it pleases them, and most often when it does not please me, as they do now.’ ‘Jesus, Sire! is it possible?’ I replied. ‘That is to treat you like a scholar,
  • 53.
    LOUIS XIII., KINGOF FRANCE. From an engraving by Picart. and make themselves your tutors, who come to give you a lesson when it pleases them. You ought, Sire, to conduct your affairs like a King, and every day, on your arrival at the place where you purpose to spend the night, one of your Secretaries of State should come to tell you if there be any news of importance which requires the assembling of your Council, and then you should send for them to come to you, either at that same hour, or at one which will be most convenient to you. And, if they have anything to tell you, let them inform you of it first, and then send them word when they are to come to you. It was thus that the late King your father conducted his affairs, and your Majesty ought to do likewise; and if they [the Ministers] should come to you otherwise [i.e., without being sent for], to send them away, and to tell them of your intention firmly, once for all.’ “The King took the representations I had made him in very good part, and said that, from that moment, he would put my counsel into practice; and he went on talking to the Maréchal de Praslin and myself. When our
  • 54.
    conversation had continuedfor some little time, Monsieur le Prince approached the King and said: ‘Sire, these gentlemen [the Ministers] await you to hold the council.’ The King turned to Monsieur le Prince with an angry countenance and exclaimed: ‘What council, Monsieur? I have not sent for them. I shall end by being their valet; they come when they please, and when it does not please me. Let them go away, if they wish to, and let them come only when I shall send for them; it is for them to consult my convenience and to send to inquire when that may be, and not for me to consult theirs. I desire that, at the end of each day’s journey, a Secretary of State should present himself at my lodging to inform me what news there is, and, if it be of importance, I will name a time to deliberate upon it; but I will never allow them to name it; for I am their master.’ “Monsieur le Prince was a little surprised at this response and was very curious to know from what shop it came. He went back to tell them [the Ministers], who requested him to inform the King that they were come merely to receive the honour of his commands, as courtiers, and not otherwise, and that if only his Majesty would speak a word to them, they would go away. The King did so, but very brusquely, and it was:— “‘Messieurs, I am going to play cards with this company.’ Upon which they made him a profound reverence and withdrew, very astonished.” The Ministers soon ascertained whom they had to thank for the very mortifying rebuff which they had received from the King, and were more incensed than ever against Bassompierre. The latter, who had been on very friendly terms with the Cardinal de Retz until his Eminence’s designs upon the King had brought their interests into collision, went to see him the next day and assured him that, so far as he himself was concerned, he was still his very humble servant. But he told him that he had no love for his colleagues, Schomberg and De Vic, and wished them to know it. The Cardinal begged him to be reconciled with them, but within forty-eight hours two incidents occurred which removed all hope of this. It happened that, the following evening, news arrived that the Maréchal de Roquelaure was dangerously ill and that his recovery was considered hopeless. “Upon which,” says Bassompierre, “these gentlemen [the three Ministers] and Monsieur le Prince went in a body to the King to demand the charge of marshal of France, which he [Roquelaure] had, for M. de Schomberg. The only answer which the King made them was to say: “And
  • 55.
    Bassompierre—what shall hebecome?” This crude reply deeply affected M. de Schomberg, and from that day we ceased to speak to one another.”[3] The second incident, which followed closely upon the first, served to embitter still further the relations between these two gentlemen. “It happened on the morrow that the King only travelled one stage,[4] at which we [Créquy and himself] were annoyed, because we saw that these gentlemen [the Ministers] were purposely delaying the King’s arrival, thinking, if time were allowed them, to usurp the authority before he had seen the Queen his mother and the old Ministers. The Maréchal de Créquy and I, while warming ourselves in the King’s wardrobe, complained of these short journeys, upon which the Comte de la Roche-guyon told us that they were made out of consideration for the French and Swiss Guards, who otherwise would be unable to follow us. We said then that this consideration ought not to occasion such a long delay; that we, who were respectively in command of the two regiments of Guards, did not complain, that the Guards would march so far as the King pleased, and that we could make them do what we wished. Out of these last words, which were reported to the Ministers, they proceeded to compound three dishes for the King, saying that we boasted of making the two regiments of Guards do what we wished, and that we could turn them in whatever direction we pleased. They attacked the King on his weak side, and he was angry at seeing that we were compromising his authority. “The evening before he arrived at Poitiers, he told me that he desired to speak to me on the following morning, and said to me: ‘I promised to tell you all that might be said to me concerning you. That is why, since it has been reported to me that you were boasting of being able to persuade the Swiss to do all that you wished, and even against my service, I desired to make you understand that I do not approve of such discourse being held, and less by you than by another, seeing that I have always had entire confidence in you.’ “‘God be praised, Sire,’ I answered, ‘that my enemies, seeking every means to injure me, are unable to find anything save what is easy for me to avert and bring to naught. This accusation is of that quality, and you can learn the truth from their own mouths, although it is but little accustomed to issue from them. Ask them, Sire, on what subject I said that I would make the Swiss do what I wished, and if they do not tell you that it was on that of
  • 56.
    their making longor short marches, about which M. de Créquy and I were complaining to one another, since they make arrangements for your Majesty to travel a shorter distance each day to return to Paris than a parish procession would cover, I am willing to lose my life. And your Majesty can judge whether that touches you or not, and whether you ought to regard this discourse as a boast of being able to employ the Swiss against your service.’” The King did not accept Bassompierre’s proposal to confront him with his accusers; but he sent for two valets of his wardrobe, who had been present during the conversation between him and Créquy, and questioned them in his presence. They confirmed what Bassompierre had just told him, and his Majesty expressed himself satisfied that he had spoken the truth. This clumsy attempt to injure Bassompierre recoiled upon its authors in a manner that was distinctly embarrassing for them. A few days later, when the King was at Châtellerault, the Ministers proposed that he should travel on the following day only so far as La Haye-Descartes, on the right bank of the Creuse, a very short day’s journey. Louis, however, announced his intention of going on to Sainte-Maure, adding significantly that it seemed to him that, if they could have their way, he would not reach Paris for three months. These squabbles between the jealous and spiteful courtiers and Ministers who surrounded Louis XIII, to all appearance so trifling, were in reality of great political importance. For they were all manœuvres in the struggle to dominate the indolent and fickle mind, and, with it, the policy, of this young monarch, who, while so punctilious in exacting all the respect which he considered due to his royal dignity, was ready to surrender the sovereign authority to the favourite of the moment. And upon the result of that struggle hung the destinies, not only of France, but of Europe. On January 27, Louis XIII arrived in Paris, where Marie de’ Medici was awaiting him. The meeting between them was most affectionate. Marie expressed the greatest joy at seeing her son return to his capital so well in health and now indeed the master; and the King replied that he intended to prove to everyone that never did son love or honour his mother more. Marie believed him too easily. Louis XIII was twenty-one and not nearly so manageable as he had been as a lad; and he feared the authoritative temper
  • 57.
    of Richelieu, ofwhom the Nuncio Corsini wrote to Gregory XV that he was “of a character to tyrannise over both the King and his mother.” Besides, to re-establish her influence over her son it was necessary for the Queen- Mother to keep him near her, and circumstances were to render this impossible. Notwithstanding that the country was rent by civil war, and that so many distinguished families were in mourning for relatives fallen before Montauban, the winter in Paris seems to have been as gay as ever. “The Court was very beautiful, and the ladies also,” says Bassompierre, “and during the Carnival several fine comedies and grand ballets were performed.” In the middle of March, however, a most unfortunate incident occurred, which cast a gloom over both Court and capital. Early in 1622, to the great joy of the nation, the Queen had been declared pregnant. Prayers were offered up in all the churches in France for her safe delivery, and all those about her Majesty’s person were strictly enjoined not to allow her to exert herself, to which instructions, however, they unfortunately appear to have paid but little heed. One evening, Anne of Austria and a party of courtiers, amongst whom were the widowed Duchesse de Luynes and Mlle. de Verneuil, went to spend the evening with the Princesse de Condé, who was ill and confined to her bed. On their way back to the Queen’s apartments, they were passing through the grande salle of the Louvre, when Madame de Luynes and Mlle. de Verneuil seized their royal mistress by the arms and began to run. They had not, however, gone many paces when the Queen tripped and fell on her face. A few hours later, to the general dismay, it was known that her Majesty had had a miscarriage. Louis XIII was furiously indignant, as well he might be, and wrote to the two delinquents with his own hand, ordering them to retire from Court. It is probable that the disgrace of Madame la Connétable, against whom, as we know, his Majesty already had a grievance, might have lasted some considerable time, had not her marriage with the Duc de Chevreuse, who stood high in the King’s favour, paved the way for her return.
  • 58.
    CHAPTER XXVII Question ofthe Huguenot War the principal subject of contention between the two parties —Condé and the Ministers demand its continuance—Marie de’ Medici, prompted by Richelieu, advocates peace—Secret negotiations of Louis XIII with the Huguenot leaders —Soubise’s offensive in the West obliges the King to continue the war—Louis XIII advances against the Huguenot chief, who has established himself in the Île de Rié— Condé accuses Bassompierre of “desiring to prevent him from acquiring glory”— Courage of the King—Passage of the Royal army from the Île du Perrier to the Île de Rié —Total defeat of Soubise—Siege of Royan—The King in the trenches—His remarkable coolness and intrepidity under fire—Capitulation of Royan—The Marquis de la Force created a marshal of France—Conversation between Louis XIII and Bassompierre— Diplomatic speech of the latter. Meantime, the struggle between the two parties, which had begun on the journey from Bordeaux to Paris, continued at the Louvre. Condé and his allies were unable to prevent the Queen-Mother from entering the Council, but they succeeded in excluding the man who possessed her mind. Richelieu spoke through her mouth, however, and those who remembered her regency were astonished at the prudence, address, and firmness which she now displayed. The war against the Huguenots was the principal subject of contention. Marie de’ Medici, under the influence of Richelieu, the old Ministers the Chancellor Sillery and Jeannin, Puisieux, and the generals, wished for peace; Condé and the new Ministers demanded the continuance of the war. Condé saw in the war the means of separating the King from his mother, and commanding the army in the name of Louis XIII. A superstitious hope made him particularly anxious to have large military forces at his disposal. An astrologer had predicted to him that he would become King at the age of thirty-four, and he was now in his thirty-fourth year. He desired, therefore, to prove his devotion to the Catholic religion, and to be in a position to seize the crown at the date when Louis XIII and his younger brother were apparently destined to die. Marie brought to the Council the arguments with which Richelieu had furnished her on the grave situation of external affairs. The House of Austria, she pointed out, was everywhere aggressive and everywhere successful. In Germany, the Empire had reduced Bohemia to submission.
  • 59.
    The unfortunate ElectorPalatine, deprived of the Upper Palatinate by Maximilian of Bavaria, and of the Lower Palatinate by Tilly, General of the Catholic League, and Gonzalvo de Cordoba, commander of the Spanish forces, had been obliged to take refuge in Holland. Philip IV, on the expiration of the twelve years’ truce with Holland in 1621, had called upon the Dutch to acknowledge his supremacy, and, on their refusal, had attacked them. The Spaniards mocked at the Treaty of Madrid, and, so far from evacuating the Valtellina, as they had engaged to do, had invaded the country of the Grisons, in concert with the Archduke Leopold, and obliged them to submit to a humiliating treaty which deprived them of the suzerainty of the Valtellina. Prompted by Richelieu, Marie urged upon the Council the imperative necessity of pacifying France, in order to be in a position to intervene in the affairs of Europe and arrest the alarming progress which the House of Austria was making. “To enter into a civil war,” said she, “is not the road to arrive at it, as was manifest during the siege of Montauban, when, in place of executing the Treaty of Madrid, they [the Spaniards] pushed their armies further and advanced by much their design to arrive at the monarchy of Europe. Although assuredly it is better to perish rather than abate anything of the royal dignity, it seems that it [the dignity] is preserved, if peace and the pardon of their crimes is given to them [the Huguenots], without restoring to them any of the places of which they have been deprived.” Condé and his allies pretended, on the contrary, that it was necessary before everything, and at all costs, to subdue the internal enemy and to check the audacity of the Huguenots, immensely encouraged by the successful resistance of Montauban. La Force and his sons had resumed hostilities in Guienne, and many places in that province which had submitted to the King had revolted anew. In Lower Languedoc, masters of Nîmes, Montpellier, Uzès, Privas, and a number of smaller towns, the assembly of the “circle,” had ordered or, at any rate, authorised, the most disgraceful excesses, and between thirty and forty churches, amongst which were some of the finest monuments of the Middle Ages, had been ruined. In the West, the Rochellois were masters of the sea; Saint-Luc, who had vainly endeavoured to make head against them, was blockaded in the port of Brouage; and a multitude of privateers preyed upon the commerce of the Atlantic coast.
  • 60.
    At the beginningof 1622, the Rochellois and the predatory nobles who made common cause with them conceived the bold project of occupying the mouths of the Loire and the Gironde, in order to hold all the commerce of those two rivers to ransom. The revolt of Royan, on the right bank of the Gironde, and the occupation of two other strong points had already resulted in the virtual blockade of that river; while Soubise, violating the oath which he had taken at the capitulation of Saint-Jean-d’Angély not to bear arms again against his sovereign, charged himself with the Loire, descended with a considerable force on Sables d’Olonne, in order to raise the Protestants of Poitou, and overran all the country up to the suburbs of Nantes. Thus tricked by the Spaniards and braved by the Protestants, Louis XIII had to choose between his enemies. For a time he appeared inclined to listen to the advice of his mother—or rather of Richelieu—and, unknown to Condé and his supporters, authorised Lesdiguières to negotiate with Rohan. “And that nothing might be revealed,” says Bassompierre, “save to M. de Puisieux and myself, whom he commanded to keep the affair very secret, he wished that M. des Lesdiguières sent duplicate despatches; one copy to be read and deliberated upon in the Council; the other, which was private and addressed to M. de Puisieux, to be communicated only to the King, who informed me of its contents.” The negotiations progressed so far that Louis promised to receive a deputation from the Reformed churches, and threatened the Spanish Ambassador to go to Lyons and organise an army to march to the assistance of the Grisons, if Spain did not forthwith withdraw from their country and the Valtellina. But the progress of Soubise and the disobedience of d’Épernon, who declined to send troops from his governments of Saintonge and the Angoumois to the assistance of the hard- pressed Royalists of Poitou, gave the victory to Condé and his adherents; the King decided to march in person against Soubise, and, on March 20, without waiting for the arrival of the Protestant deputies, he left Paris for Orléans, accompanied by the Queen-Mother, who was determined to keep within reach of him so long as she could. From Orléans, the King, still accompanied by Marie, proceeded to Blois, and thence by water to Nantes, where the army was to assemble, and where on the 11th he was joined by Bassompierre, who had been summoned by courier from Paris. On his arrival at Nantes, Louis XIII learned that Soubise was endeavouring to establish himself in the Île de Rié, a maritime district of
  • 61.
    Lower Poitou, separatedfrom the mainland by vast salt marshes and small rivers, which at high tide the sea rendered impassable. If the Huguenot leader were permitted to entrench himself there, it was a position from which it would be exceedingly difficult to dislodge him; but this the King resolved not to allow him time to do; and, leaving the Queen-Mother, who had fallen ill, at Nantes, like a true son of Henri IV, he marched at once upon the enemy. The Royal army consisted of from 10,000 to 12,000 men; that of Soubise from 6,000 to 7,000; but the latter had the advantage of position and seven pieces of cannon; while the attacking force was, of course, unable to transport its artillery across the marshes. The enterprise would therefore have been a hazardous one, with a watchful and resolute enemy to contend with. On this occasion, however, Soubise showed neither the vigilance of a general nor the courage of a soldier. The approach of the enemy much sooner than he had foreseen appears to have disconcerted his plans altogether, and, instead of attempting to defend the approaches to the Île de Rié, he thought only of re-embarking his troops in a squadron of vessels which he had at his disposal, and making his escape with the plunder he had collected to La Rochelle. In the afternoon of April 14, Marillac, with a small force of infantry, occupied the Île du Perrier, adjoining the Île de Rié, and early on the following morning Bassompierre was ordered by Condé to follow with the rest of the infantry. Condé then proposed that they should ford an arm of the sea “wide as the Marne,” which separated the islands of Perrier and Rié, and where at low tide, which would be at midday, the peasants had told him, the water would be only waist-deep. Bassompierre, however, protested against this, pointing out that, if the enemy offered the least opposition to their passage, the tide would rise before half the troops had crossed, and even if they were allowed to cross unopposed, they would find themselves at a great disadvantage without cavalry or cannon. He added that, apart from these considerations, he ought certainly to await the arrival of the King. “For if you defeat M. de Soubise,” said he, “he [the King] will take it ill that you have not shared the honour of the victory with him; and, if some reverse befalls you, he will blame your precipitation, and will accuse you of not having wished or deigned to wait for him.” Monsieur le Prince took this remonstrance in very bad part, and declared that he saw plainly that Bassompierre was “of the cabal who desired to
  • 62.
    prevent him fromacquiring glory.” But he sent him to the King to beg him to come at once with the cavalry, and when his Majesty arrived on the scene, it was decided to wait until midnight and to cross to the Île de Rié at another spot, where they were informed there would be less water. In the course of the evening, Louis XIII displayed for the first time that cool courage which he invariably afterwards showed in war, and which, if it had been combined with the same degree of moral resolution, would have made him a really remarkable man:— “While the King, stretched on a miserable bed,” says Bassompierre, “was consulting with us about the passage, a great alarm spread throughout the camp that the enemy was upon us; and, in an instant, fifty persons rushed into the King’s chamber, who declared that the enemy was at hand. I knew well that this was impossible, since it was high tide, and they could not pass. Instead, therefore, of being alarmed, I wished to see how the King would take it, in order that I might regulate the proposals which I might in future have to make to him, according to the firmness or agitation which he displayed. This young prince, who was lying down on the bed, sat up on hearing this rumour, and, with a countenance more animated than usual, said to them: ‘Gentlemen, the alarm is without, and not in my chamber, as you see; it is there you must go.’ And, at the same time, he said to me: ‘Go as quickly as you can to the Bridge of Avrouet, and send me your news promptly. You, Zamet, go out and find Monsieur le Prince, and M. de Praslin and Marillac will stay with me. I shall arm myself and place myself at the head of my Guards.’ I was delighted to see the confidence and judgment of a man of his age so mature and so perfect. The alarm was, as I supposed, a false one, arising from a very trifling incident.” All the arrangements for the passage of the army had been entrusted to Bassompierre. The troops assembled at ten o’clock, and a little before midnight the order to advance was given. At the spot where the Guards were to cross, however, the water was so deep that they sent to inform Bassompierre that it was impossible to pass. He went there, and finding that it would be a very difficult undertaking, led them to another ford, by which he crossed himself to the Île de Rié, and saw no sign of any enemy. He returned and reported that the ford was practicable and that their passage would be unopposed, and the whole army passed without mishap; though when Bassompierre crossed for the second time, at the head of the
  • 63.
    rearguard, the tidewas beginning to rise, and the water was nearly up to his chin.[5] On reaching the shore, the troops encamped and lighted a great number of fires to dry their clothes. At daybreak they were formed in order of battle, and, after a march of about two leagues, came in sight of the enemy. Soubise and his cavalry, to the number of five or six hundred, fled at once in the direction of La Rochelle, without striking a blow. Part of the infantry had already embarked in the launches that had arrived to take them off; the rest threw down their arms and demanded quarter. But this was refused to the majority of them, and more than 1,500 were shot or cut down in cold blood; while as many more were taken prisoners and sent to the galleys. The rest fled across the marshes, in which some of them were drowned, while many others were slain by the troops of La Rochefoucauld, governor of Poitou, or by the peasants, furious at the devastation which the Huguenots had committed. Only some four hundred succeeded in effecting their escape and making their way to La Rochelle. Leaving a force under the Comte de Soissons to watch La Rochelle on the land side, while Guise was directed to blockade it by sea, Louis XIII marched southwards, with the intention of raising the blockade of the Gironde by the reduction of Royan. During the siege, the King gave further proofs of that courage and presence of mind which Bassompierre had admired before the attack on the Île de Rié. “That same evening I went to the King in his quarters, and he told me that he was coming to see our trench at five o’clock the next morning ... and desired me to await him at the commencement of it. He came, accompanied by M. d’Épernon and M. de Schomberg. It was the first time he had ever been in the trenches, and he did me the honour to say to me: ‘Bassompierre, I am a novice here; tell me what I must do, so that I may not make mistakes.’ In this I found little difficulty, for he was more prodigal of his safety than any of us would have been, and mounted three or four times on to the banquette of the trench, where he was exposed to the fire of the enemy, to reconnoitre. And he stayed there so long that we trembled at the danger he was incurring, which he braved with more coolness and intrepidity than an old captain would have shown, and gave orders for the work of the following night as though he had been an engineer. While he was returning, I saw him do what pleased me extremely. After we had
  • 64.
    remounted our horses,at a certain passage which the enemy knew, they fired a cannon-shot, which passed two feet above the head of the King, who was talking to M. d’Épernon. I was riding in front of him, and turned round, fearing that the shot might have struck him. ‘Mon Dieu, Sire,’ I exclaimed, ‘that ball was near killing you!’ ‘No, not me,’ said he, ‘but M. d’Épernon.’ He neither started nor lowered his head, as so many others would have done; and afterwards, perceiving that some of those who accompanied him had drawn aside, he said to them: ‘What! Are you afraid that they will fire again? They will have to reload.’ I have witnessed many and various actions of the King in several perilous situations, and I can affirm, without flattery or adulation, that I have never seen a man, not to say a king, who was more courageous than he was. The late King, his father, though, as everyone knows, celebrated for his valour, did not display a like intrepidity.” It is not the degree, but the kind of courage, which is remarkable at his age. Bassompierre, however, relates an instance of equal coolness in a boy, who had not the same strong motive to self-possession as was furnished by the consciousness of being the object of the whole army’s attention: “The enemy had constructed a barricade in their fosse, on the side of the sea, and a palisade, which hindered us from being entirely masters of their fosse. I sent my volunteer, a young lad of sixteen, to reconnoitre it. This lad had, the previous year, executed with other camp-boys the most hazardous works at the siege of Montauban, which the soldiers refused to undertake. He had received several wounds, amongst others a musket-ball through the body, of which I got him cured. This young rogue undertook a number of dangerous works by the piece, and the camp-boys worked under him and made a great deal of money. He went to reconnoitre this barricade with the same bearing and as much boldness as the best sergeant in the army; and after getting a musket-ball through his breeches and another through the brim of his hat, returned to us and made his report, which was very judicious.” Royan capitulated on May 11, and shortly afterwards La Force surrendered the town of Sainte-Foy and returned to his allegiance, in return for the bâton of Marshal of France. Louis XIII, who had been given to understand that both Bassompierre and Schomberg were deeply mortified that a rebel should have been created a marshal before either of them, sent
  • 65.
    for the formerand said to him: “Bassompierre, I know that you are angry that I am making M. de La Force Marshal of France, and that you and M. de Schomberg complain of it, and with reason; but it is not I who am the cause of it, so much as Monsieur le Prince, who counselled me to do it, for the good of my affairs, and in order to leave nothing behind me in Guienne which might prevent me passing promptly into Languedoc. Nevertheless, be sure that what you desire I shall do for you, whom I love and hold as my good and faithful servant.” Bassompierre tells us that at that time he had no particular desire for the office of marshal, “since, in his opinion, it was that of an old man, while he wished to play the part of a gallant of the Court for some years longer.” He therefore assured his Majesty that he had been entirely misinformed, and that, so far from being annoyed at La Force’s appointment, he regarded it as a most proper one, since he was an old man and a soldier of great experience, who had been promised the bâton by the late King and would have received it, if Henri IV had lived another month; that, although he had been a rebel, he was one no longer; and that it was “a signal example of the kindness of the King to forget the faults of his servants, in order to remember and recompense their merits and their services.” And he added that he did not aspire to the office of marshal or any other charge, unless his Majesty “out of pure kindness and desire to recognise his service,” wished to confer it upon him, and that he “very humbly besought him never to allow any consideration for him to prevent him doing what he judged to be for the good of his service.” This diplomatic speech greatly pleased the King, who thanked Bassompierre and told him that he might rely on him to advance his interests. He then sent for Schomberg, who, much less tactful than his colleague, pressed his Majesty to make him a marshal conjointly with La Force, and proposed that Bassompierre should be created one also, “though this was chiefly in order to strengthen his own request.”
  • 66.
    CHAPTER XXVIII Condé andhis allies offer to secure for Bassompierre the position of favourite, if he will join forces with them to bring about the fall of Puisieux—Refusal of Bassompierre— Condé complains to Louis XIII of Bassompierre’s hostility to him—Bassompierre informs the King of the proposal which has been made him—Louis XIII orders Monsieur le Prince to be reconciled with Bassompierre—Siege of Négrepelisse—The town is taken by storm—Terrible fate of the garrison and the inhabitants—Fresh differences between Condé and Bassompierre—Discomfiture of Monsieur le Prince—Bassompierre placed temporarily in command of the Royal army, captures the towns of Carmain and Cuq- Toulza—Offer of Bassompierre to resign his claim to the marshal’s bâton in favour of Schomberg—Surrender of Lunel—Massacre of the garrison by disbanded soldiers of the Royal army—Bassompierre causes eight of the latter to be hanged—Lunel in danger of being destroyed by fire with all within its walls—Bassompierre, by his presence of mind, saves the situation—Schomberg and Bassompierre—The latter is promised the marshal’s bâton. At Moissac, where Louis XIII arrived in the first week in June, Condé approached Bassompierre and invited him to meet him “in a kind of chapel which is in the cloister of the abbey,” as he desired to confer with him on a matter of great importance. Thither Bassompierre repaired and found the prince in the company of his allies, Retz and Schomberg. All three forthwith began to inveigh against Puisieux, whose presumption, they declared, they were no longer able to endure. Although only a Secretary of State, he was admitted to greater intimacy with the King than Monsieur le Prince himself, sought to prejudice his Majesty against those with whom he was not on good terms, conducted separate negotiations, which he declined to communicate to them, and prevented the execution of the decisions of the Council, if he had not previously approved of them. Since the death of the late Constable, they had, they said, endeavoured “to prevent the King from embarking in a new affection,” and they were of opinion that it would be better for his Majesty to have no favourite. “However, since they saw that his inclination was to be dominated by someone, they preferred that it should be by a brave man, of high birth and esteemed for his knowledge of the arts of peace as well as of those of war, rather than by a man of the pen like M. de Puisieux, who would turn everything upside down; and that they were all resolved to conspire to bring
  • 67.
    about his ruin,as they were to assist in the aggrandisement of my fortune, and to persuade the King, who was already favourably inclined towards me, to favour me entirely with the honour of his good graces, provided that I were willing to promise them two things: the one, to co-operate with them to ruin M. de Puisieux and to detach myself entirely from his friendship; the other, to associate myself entirely with them and combine our designs and counsels, in the first place, for the good of the King’s service, in the second, for our common interest and preservation. And they begged me to come to a prompt decision upon this matter and to acquaint them with it.” Bassompierre felt quite certain that the proposal which had just been made to him was nothing but a skilfully-baited trap, and that the intention of Condé and his friends was “to penetrate his design and then to reveal it to the King, and that they desired to make use of him to ruin M. de Puisieux, and afterwards with greater facility to ruin him.” “I accordingly replied that I was unable to understand what necessity there was for the King to have a favourite, since he had dispensed with one so easily for eight months; that his favourites ought to be his mother, his brother, his relatives and his good servants, wherein he would be following the example of the King his father, and that if some fatality inclined him to have one, the choice and the election ought to be left to him; that I had never heard tell of any prince who took his favourites according to the decrees of his council; but that, however that might be, it would not be I who would occupy that place, because I did not deserve it; because, also, the King would not wish to honour me with it, and because, finally, I would not accept it; that I aspired to a moderate degree of favour, and a fortune of the same kind acquired by my virtue and by my merit, and which might be securely preserved; that my lavish expenditure, and the little care I had taken up to the present to amass wealth, were sufficient proofs that I aspired rather to glory than to profit; that I wished to seek a moderate and a secure fortune, and despised favour to such a degree that, if it were lying on the ground before me, I should not condescend to stoop and pick it up; and that such was my unalterable resolution, which did not allow me to take advantage of their good-will towards me, for which I rendered them very humble thanks.”
  • 68.
    As for theircomplaints about Puisieux, he said, it seemed to him that they were really complaining of the King and questioning his Majesty’s right to confer privately with, and demand advice from, whichever of his Ministers he pleased. Puisieux was his [Bassompierre’s] friend, and had always behaved as such, and, so long as he continued to do so, he declined to be a party to any intrigue against him. Condé then warned Bassompierre that a time might come when he would regret having lost his friendship and that of his allies in order to preserve that of Puisieux; to which Bassompierre replied that he would be “extraordinarily grieved to lose their good graces, but that the consolation would remain to him of not having lost them through any fault of his own, and that he would never purchase those of anyone at the price of his reputation.” That evening, Louis XIII decided to send a body of two hundred cavalry to scout in the direction of Montauban, and Valençay, who was lieutenant of Condé’s company of gensdarmes, asked to be allowed to go, and to take with him both his own men and Monsieur le Prince’s company of light horse; and to this the King consented. Condé was not at the council of war, and did not learn of what had been done until later in the evening, when he was extremely angry and went to the King to complain that an affront had been put upon him by sending his two companies of horse away without his knowledge, and that he felt quite certain that it was Bassompierre who had suggested it. The King assured him that Bassompierre had had nothing to do with the affair, and that Valençay had himself asked for the commission, which he had given him, never imagining that Monsieur le Prince would take it ill. Condé, however, insisted that Bassompierre must have been at the bottom of it, and declared that he was hostile to him. When he had gone, the King sent for Bassompierre and told him of what the prince had said, upon which he deemed it advisable to inform his Majesty of the proposal which Condé had made him that morning in the chapel. “But,” he says, “as it is very dangerous to be in the disfavour of a person of that rank who is your general, I begged the King very humbly either to reconcile us or to permit me to retire, since I did not wish to draw his hatred and his anger upon me.” This the King promised to do, and the next evening, when the army had encamped at Villemode, near Montauban, he came into the camp, and having praised Bassompierre for the arrangements which he had made, he
  • 69.
    turned to Condéand said: “Monsieur, yesterday you were angry with him without cause, and you can learn from Valençay whether Bassompierre was in any way responsible for his being sent away. I beg you, for love of me, to live on good terms with him, for I assure you he is your servant; and, if he were lost to this army, you know yourself whether it would be our fault.” Condé promised to do as the King desired, and the same evening offered his apologies to Bassompierre, who begged him to regard him as his very humble servant, and that “when he happened to have any reason to be displeased with him, to do him the honour of telling him of it, and, if he did not give him satisfaction in the matter, to be angry with him with all his soul, and not before.” On the following day—June 8—the army arrived before Négrepelisse, a little town on the left bank of the Aveyron. Louis XIII and his whole army were bitterly incensed against the inhabitants of Négrepelisse, who, one night during the previous winter, had revolted and massacred four hundred men of the Vaillac Regiment who had been placed in garrison there; while a report was current among the soldiers that, during the siege of Montauban, the sick and wounded of the Royal army who had been transported thither had been poisoned. However, as the town was believed to have returned to its allegiance, provided they admitted the King, there would not appear to have been any intention of punishing the inhabitants. But when the quartermaster who had been charged to select suitable quarters for his Majesty, approached the gates, he found them closed, and was received with a volley of musket-shots. On learning of what had occurred, the King ordered Bassompierre, who was with the advance-guard, to invest the town, which he proceeded to do; but, on going forward to reconnoitre the place with Praslin and Chevreuse, he had a narrow escape of his life, being fired upon from a distance of twenty paces by a party of the enemy, whom he had mistaken for some of his own men. “There was not in Négrepelisse,” says Bassompierre, “anything better than a musket; no munitions of war save what each inhabitant might have had to go out shooting; no foreign soldier, no chief to command them; and the place, though it might have offered some resistance to a provincial force, was quite incapable of resisting a Royal army. Nevertheless, the inhabitants would neither consent to surrender nor even to parley.”
  • 70.
    The probable explanationis that the townsfolk were convinced that the King was bent upon their destruction, and that no terms which he might consent to give them would be observed; and that they had therefore determined to sell their lives for what they might be worth. On the 9th, a battery of seven cannon was got into position close to the walls, and, although the enemy’s musketry-fire was very effective, and caused many casualties amongst the gunners, by the following morning a considerable breach had been made. The besieged endeavoured to repair it by a barricade of carts, but this was of little avail, and the town was quickly taken by assault. Louis XIII, infuriated by the obstinacy of the inhabitants, had given orders that they were to be treated as they had treated his soldiers some months before, and every man capable of bearing arms was put to the sword, with the exception of a few who succeeded in escaping into the château. The troops exceeded the pitiless orders of the King, and the majority of the women were violated and many murdered, together with their children; while the town was pillaged and burned almost to the ground. The officers appear to have done their best to protect the women and to save the town; but, as so often happened in those days when places were taken by assault, the soldiers were quite out of hand, and it was impossible to restrain them.[6] The château held out until the following day, when it surrendered at discretion, and twelve or fifteen of those found there were taken and hanged. The reconciliation between Bassompierre and Condé was of very short duration, for, a day or two later, the prince accused him in a council of war of questioning the orders which were given him. Bassompierre retorted that he had a right to his opinion, and that “if his mouth were to be closed, he should retire from the Service. The King thereupon took his part, and was very angry with Monsieur le Prince.” Further differences arose between them respecting the investment of Saint-Antonin, and, as Condé refused to be guided by his advice, Bassompierre begged to be permitted not to serve during the siege, and his request was granted. Marillac was then appointed to the temporary command of Bassompierre’s troops; but the officers of the Guards refused to take their orders from him, as did those of the Navarre Regiment. Condé was furious and, going to the King, accused Bassompierre of “making cabals and
  • 71.
    mutinies in hisarmy,” and said that he “deserved punishment and even death.” And that gentleman happening to enter the royal presence a few moments later, he denounced him to his face. Bassompierre denied the charge, and said that the refusal of the officers of the Guards and of Navarre to serve under Marillac was not due to any action on his part, but to the poor opinion they entertained of Marillac’s military capabilities, and that if some other officer were appointed, they would obey him readily enough. With this explanation Louis XIII professed himself satisfied, and Monsieur le Prince retired discomfited. If we are to believe Bassompierre, Condé would appear to have bungled the siege of Saint-Antonin pretty badly, and an imprudent attempt to take the place by assault was repulsed with heavy loss. However, on June 22 the town surrendered. A few days later, Bassompierre and the prince again came into collision. Condé had proposed in the Council to attack Carmain, a nest of Huguenots which was a great annoyance to the people of Toulouse, who had petitioned that its reduction should be undertaken;[7] but Bassompierre objected that to conquer these small places was to waste time which might be more usefully employed in besieging important strongholds of the enemy like Nîmes and Montpellier. It was decided to follow his advice, whereat “Monsieur le Prince’s bile was stirred against him,” and he left the Council in anger, complaining loudly that Bassompierre had prevented Carmain from being invested. Some Huguenot gentlemen happening to overhear him, sent to inform the authorities of that town that the Royal army had no intention of laying siege to it, in consequence of which a body of 500 men who were on their way from Puylaurens to reinforce the garrison received orders to return. Bassompierre, who had been ordered to lead the army to Castelnaudary, while the King and Condé went to visit Toulouse, learned of the return of this reinforcement, and aware that, deprived of its assistance, the people of Carmain would probably consider themselves incapable of withstanding a siege, determined to make an attempt to trick them into surrender. He accordingly appeared before the town, with all the paraphernalia for a siege: carts loaded with gabions, platforms for the batteries, and so forth, although he, of course, had no intention of undertaking it, since he had not received any orders to that effect, and, besides, had only two siege-guns with him. He then summoned it to surrender, vowing to make a terrible example of it in the event of a refusal,
  • 72.
    and to treatit as Négrepelisse had been treated; and the inhabitants, completely deceived, offered to parley forthwith, and early on the following morning, terms of capitulation having been arranged, the place surrendered (June 30). The previous night part of the Piedmont Regiment, which Bassompierre had detached against the neighbouring town of Cuq-Toulza, had carried that place by assault, after blowing in the gate with a petard. So that within a few hours two towns had been taken, one of them without a blow being struck. Not a little elated by this double success, Bassompierre placed the army in charge of Valençay, and repaired to Toulouse to report to the King. “I arrived,” says he, “at the moment when the King was holding his council and was reprimanding Monsieur le Prince, because, when the Parlement and aldermen of Toulouse had come to do him homage, Monsieur le Prince had said that the cowardice of M. de Bassompierre had prevented the King from attacking Carmain, as, though he had counselled him to do it, I had dissuaded him. When the King was informed that I was at the door, he wondered what could have caused me to quit the army; but, when he ordered me to be admitted, I told him that I wished to bring him myself the news of the capture of Carmain and Cuq and to receive his commands upon other matters which I wished to propose to him. Then Monsieur le Prince rose and came to embrace me, telling me that he had done wrong to say what he had said, and that he would repair it by saying much good of me.... It is impossible to describe the joy with which the people of Toulouse received the news of this capture. They caused a splendid lodging to be made ready for me; and the aldermen came to thank me, and to invite me to dine on the morrow at the Hôtel-de-Ville, where they would hold a grand assembly for love of me, and a ball to follow. But I begged them to excuse me, on the ground that it was necessary for me to return promptly to the army.” Bassompierre returned to the army accompanied by Praslin, who took over the command. The following day he met with what might have been a very severe accident, his horse stumbling and falling into a ditch on top of him. However, he escaped with nothing worse than a badly bruised foot. On July 2, the army reached Castelnaudary, having snapped up the little town of Le Mas-Saintes-Puelles on the way, and on the 5th the King joined it. His
  • 73.
    Majesty was unwell,suffering, says his physician Hérouard, from “sore throat, a cold, and a relaxed uvula,” and he remained for some days at Castelnaudary and kept Bassompierre with him; while the army under Praslin continued its march into Lower Languedoc. Meantime, Lesdiguières, to whom, after the death of Luynes, Louis XIII had promised the office of Constable, provided he would renounce the Reformed faith, had sent to inform the King that he was about to be received into the Catholic Church. His elevation would entail a vacancy among the marshals, and the King sent for Bassompierre and Schomberg, who had also remained at Castelnaudary, and told them that, so soon as another occurred, he would create them both marshals, but that he did not wish to promote one before the other, as he considered that their claims were equal. Schomberg, however, pressed the King to promote both Bassompierre and himself forthwith, pointing out that they could render him more useful service as marshals of France in the approaching campaign in Lower Languedoc, and that when there was another vacancy, his Majesty could leave it unfilled, which would come to the same thing. Perceiving that the King seemed very reluctant to take this course, though, at the same time, he was unwilling to refuse so pressing a request, Bassompierre, like a true courtier, came to his aid, and declared that, as he had “always preferred to deserve great honours than to possess them,” he was not so eager for the bâton as Schomberg, and would “without envy or regret” resign his claims in favour of one who was six years his senior, and one of his Majesty’s Ministers, and therefore entitled to the preference. “M. de Schomberg,” says he, “feeling that my courtesy had placed him under a great obligation, thanked me very gracefully; but the King persisted in refusing to promote one of us without the other; and so we withdrew.” On July 13, Louis XIII left Castelnaudary and proceeded, by way of Carcassonne and Narbonne, to Béziers, where he remained for some little time. Bassompierre, however, rejoined the army, which was advancing slowly towards Montpellier, and which, on August 2, laid siege simultaneously to the towns of Lunel and Marsillargues, situated about a league from one another. Marsillargues surrendered almost at once, and Lunel a few days later, the garrison of the latter place, by the terms of the capitulation, being permitted to march out with their swords only; their other weapons were to be placed in the carts which carried their baggage.
  • 74.
    Bassompierre had receivedorders to enter the town with the Guards the moment the garrison evacuated it. On his way thither, he saw great numbers of disbanded soldiers of different regiments, landsknechts and Swiss as well as French, lingering about, and felt sure that their presence boded no good, and that they were meditating an attack upon the baggage. He accordingly decided not to allow the garrison to leave until he had ridden back to the Royal camp to warn Praslin, whom he advised to take measures to prevent any such attempt. But the marshal replied that “he was not a child, and that he understood his business, and that if he [Bassompierre] would only give the necessary orders within the town, he would do the same without.” Bassompierre returned to the town and directed the garrison to march out with their baggage, after which he entered with his troops, and gave orders that the gates should be closed and the breach which the besiegers’ cannon had made strongly guarded, as he thought it not improbable that an attempt might be made to enter and pillage the place.
  • 75.
    “There was somedegree of order in the departure of the enemy,” he says, “until the baggage came in sight; but, when that appeared, all the disbanded soldiers of our army rushed upon it, before it was possible for the marshal or Portes or Marillac to prevent them, and plundered these poor soldiers, 400 of whom they inhumanly butchered.” Bassompierre, however, had the satisfaction of executing rigorous justice upon some of these ruffians:— “Eight soldiers, of different countries and regiments, presented themselves at the gates of Lunel, with more than twenty prisoners, whom they brought tied together, with the intention of entering the town. Their swords were stained with the blood of those whom they had massacred, and they were so laden with booty that they could hardly walk. Finding the gate of Lunel shut, they called to the sentries to go and tell me to give orders for them to be let in. I went to the gate in consequence of what I heard, which I found to be true. I let them in and then ordered these eight fine fellows to be bound with the same cords with which they had bound the twenty prisoners. After giving these men the booty of the eight soldiers, whom, without any form of trial, I caused to be hanged before their eyes on a tree near the bridge of Lunel, I had them escorted by my carabiniers so far as the road to Cauvisson. On the morrow, Monsieur le Prince was very pleased with what I had done and thanked me.” Two or three days after the Royal troops had taken possession of Lunel, the town narrowly escaped being destroyed, with everyone within its walls. Bassompierre was at dinner with Créquy, Schomberg, and the Duc de Montmorency when there was a violent explosion, which partially wrecked the room in which they sat, though, happily, they were unhurt. They ran out to ascertain the cause, and learned that one of a train of ammunition- waggons which was entering the town had caught fire, and that the flames had reached the powder, with the result that several houses had been destroyed and others were blazing furiously. The utmost consternation prevailed, for the explosion had occurred near the gate by which the waggons had entered, and the débris of the houses barred the approach to it, while the other gates had been blocked up by Condé’s orders; and the fire was rapidly approaching a convent, in the vaults of which a great quantity
  • 76.
    of powder wasstored. If once it reached it, the whole town would be consumed, with all the troops and inhabitants. “The confusion was extreme,” says Bassompierre, “and, as everyone was thinking only of himself and his own safety, no one ran to extinguish the fire; all the people sought only to get out of the town, but no one could find a way. At length, I caused one of the blocked-up gates to be broken open, through which everyone could get out, and, having by this expedient got more elbow-room, we removed our powder to a safe place and extinguished the fire, by which more than fifty persons had perished.” The following day Bassompierre went with a body of 500 cavalry to Villeneuve-de-Maguelonne to escort the King to Lunel, where his Majesty arrived on August 15. On the 17th, Louis XIII went to visit Sommières, which had just surrendered to his troops, and on the return journey Schomberg, whose jealousy of Bassompierre was increasing daily, finding an opportunity for private conversation with his sovereign, did not fail to turn it to account: “On the road M. de Schomberg said to the King that I was his enemy, and he begged him to believe nothing that I might say about him. The King replied that he was entirely wrong, and that I had never spoken of him except to his advantage, nor of any other person, and that Schomberg knew me very little to take me for a man who did ill turns to people. He [Schomberg] was not a little astonished by this answer.” Perceiving by Bassompierre’s manner that the King had told him of their conversation, Schomberg requested Puisieux to effect a reconciliation between them, to which Bassompierre “consented reluctantly and after he had expressed to him his sentiments.” Schomberg would appear to have possessed an unusual amount of assurance, even for a German, for, immediately afterwards, he begged the man whom he had attempted to injure to employ his good offices with the King to obtain for him the governments which d’Épernon was about to resign in order to accept that of Guienne. This cool request, however, proved a little too much for Bassompierre, whose friend Praslin also aspired to these offices; and he replied that, not only should he refuse to speak in his favour, but should oppose him, until Praslin had been provided for. Eventually d’Épernon’s governments were divided between the two, Praslin
  • 77.
    receiving Saintonge andAulnis, and Schomberg the Angoumois and the Limousin. On August 27, Louis XIII arrived at Laverune, a little to the west of Montpellier, and on the following day Lesdiguières, who had been received into the Catholic Church in the Cathedral of Grenoble on the 24th, took the oath as Constable of France; after which, to the great mortification of Schomberg, the King informed Bassompierre that it was his intention to confer the vacant marshal’s bâton upon him, and that he would give orders for the necessary patent to be made out forthwith. His Majesty’s decision to give it to Bassompierre, notwithstanding what he had told him and Schomberg a fortnight before, was no doubt due to the fact that he had just bestowed a lucrative government upon the latter and considered that he ought to be content for the present with that proof of the royal favour. However, M. de Schomberg, who was one of those whose appetite for honours and emoluments seems only to have been stimulated by attempts to satisfy it, did not view the matter in that light, and felt deeply aggrieved.