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

Immediate download Pro TypeScript: Application-Scale JavaScript Development 2nd Edition Steve Fenton ebooks 2024

Fenton

Uploaded by

yudinrubyeea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
67 views

Immediate download Pro TypeScript: Application-Scale JavaScript Development 2nd Edition Steve Fenton ebooks 2024

Fenton

Uploaded by

yudinrubyeea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Pro TypeScript: Application-Scale JavaScript


Development 2nd Edition Steve Fenton

https://textbookfull.com/product/pro-typescript-application-
scale-javascript-development-2nd-edition-steve-fenton/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


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

Pro TypeScript: application-scale javascript development


Second Edition Fenton

https://textbookfull.com/product/pro-typescript-application-scale-
javascript-development-second-edition-fenton/

textboxfull.com

Essential TypeScript 4 From Beginner to Pro 2nd Edition


Adam Freeman

https://textbookfull.com/product/essential-typescript-4-from-beginner-
to-pro-2nd-edition-adam-freeman/

textboxfull.com

Essential TypeScript: From Beginner to Pro 1st Edition


Adam Freeman

https://textbookfull.com/product/essential-typescript-from-beginner-
to-pro-1st-edition-adam-freeman/

textboxfull.com

Essential TypeScript 4 From Beginner to Pro Second Edition


Adam Freeman

https://textbookfull.com/product/essential-typescript-4-from-beginner-
to-pro-second-edition-adam-freeman/

textboxfull.com
Angular Development with Typescript Second Edition Yakov
Fain

https://textbookfull.com/product/angular-development-with-typescript-
second-edition-yakov-fain/

textboxfull.com

Pro Functional PHP Programming Application Development


Strategies for Performance Optimization, Concurrency,
Testability, and Code Brevity Aley
https://textbookfull.com/product/pro-functional-php-programming-
application-development-strategies-for-performance-optimization-
concurrency-testability-and-code-brevity-aley/
textboxfull.com

PROTEIN DOWNSTREAM PROCESSING design development and


application of high 2nd Edition

https://textbookfull.com/product/protein-downstream-processing-design-
development-and-application-of-high-2nd-edition/

textboxfull.com

Pro Functional PHP Programming: Application Development


Strategies for Performance Optimization, Concurrency,
Testability, and Code Brevity Rob Aley
https://textbookfull.com/product/pro-functional-php-programming-
application-development-strategies-for-performance-optimization-
concurrency-testability-and-code-brevity-rob-aley/
textboxfull.com

Pro jQuery in Oracle Application Express Wesley Scott

https://textbookfull.com/product/pro-jquery-in-oracle-application-
express-wesley-scott/

textboxfull.com
Pro TypeScript
Application-Scale JavaScript Development

Second Edition

Steve Fenton
Pro TypeScript
Application-Scale JavaScript
Development

Second Edition

Steve Fenton
Pro TypeScript: Application-Scale JavaScript Development
Steve Fenton
Basingstoke, United Kingdom
ISBN-13 (pbk): 978-1-4842-3248-4 ISBN-13 (electronic): 978-1-4842-3249-1
https://doi.org/10.1007/978-1-4842-3249-1
Library of Congress Control Number: 2017961729
Copyright © 2018 by Steve Fenton
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction
on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation,
computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this
legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically
for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work.
Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the
Publisher's location, in its current version, and permission for use must always be obtained from Springer. Permissions
for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution
under the respective Copyright Law.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion
and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified
as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither
the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be
made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Cover image designed by Freepik
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Gwenan Spearing
Development Editor: Laura Berendson
Technical Reviewer: Rich O’Kelly, Martin Milsom, Dan Horrocks-Burgess, Jamie Wright
Coordinating Editor: Nancy Chen
Copy Editor: Karen Jameson
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web
page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to readers on
GitHub via the book's product page, located at www.apress.com/9781484232484. For more detailed information,
please visit http://www.apress.com/source-code.
Printed on acid-free paper
For Rebecca, Lily, Deborah, Victoria, and Mum
Contents

About the Author�����������������������������������������������������������������������������������������������������xv


Acknowledgments�������������������������������������������������������������������������������������������������xvii
Introduction������������������������������������������������������������������������������������������������������������xix


■Chapter 1: TypeScript Language Features������������������������������������������������������������� 1
JavaScript Is Valid TypeScript������������������������������������������������������������������������������������������� 2
Variables��������������������������������������������������������������������������������������������������������������������������� 4
Constants������������������������������������������������������������������������������������������������������������������������� 6
Types�������������������������������������������������������������������������������������������������������������������������������� 6
Type Annotations������������������������������������������������������������������������������������������������������������������������������������ 7
Primitive Types��������������������������������������������������������������������������������������������������������������������������������������� 9
Object and Dynamic Types�������������������������������������������������������������������������������������������������������������������� 10
Enumerations��������������������������������������������������������������������������������������������������������������������������������������� 10
Union Types������������������������������������������������������������������������������������������������������������������������������������������ 13
Literal Types������������������������������������������������������������������������������������������������������������������������������������������ 14
Intersection Types��������������������������������������������������������������������������������������������������������������������������������� 15
Arrays��������������������������������������������������������������������������������������������������������������������������������������������������� 15
Tuple Types������������������������������������������������������������������������������������������������������������������������������������������� 17
Dictionary Types����������������������������������������������������������������������������������������������������������������������������������� 18
Mapped Types��������������������������������������������������������������������������������������������������������������������������������������� 19
Type Assertions������������������������������������������������������������������������������������������������������������������������������������� 20
Type Guards������������������������������������������������������������������������������������������������������������������������������������������ 21
Discriminated Unions��������������������������������������������������������������������������������������������������������������������������� 23

v
■ Contents

Operators������������������������������������������������������������������������������������������������������������������������ 24
Increment and Decrement�������������������������������������������������������������������������������������������������������������������� 24
Binary Operators����������������������������������������������������������������������������������������������������������������������������������� 25
Bitwise Operators��������������������������������������������������������������������������������������������������������������������������������� 26
Logical Operators��������������������������������������������������������������������������������������������������������������������������������� 26
Type Operators�������������������������������������������������������������������������������������������������������������������������������������� 30
Destructuring���������������������������������������������������������������������������������������������������������������������������������������� 30
Spread Operator����������������������������������������������������������������������������������������������������������������������������������� 34

Functions������������������������������������������������������������������������������������������������������������������������ 35
Optional Parameters����������������������������������������������������������������������������������������������������������������������������� 36
Default Parameters������������������������������������������������������������������������������������������������������������������������������� 37
Rest Parameters����������������������������������������������������������������������������������������������������������������������������������� 38
Overloads���������������������������������������������������������������������������������������������������������������������������������������������� 38
Specialized Overload Signatures���������������������������������������������������������������������������������������������������������� 39
Arrow Functions����������������������������������������������������������������������������������������������������������������������������������� 41
Function Currying��������������������������������������������������������������������������������������������������������������������������������� 42

Interfaces����������������������������������������������������������������������������������������������������������������������� 44
Classes��������������������������������������������������������������������������������������������������������������������������� 47
Constructors����������������������������������������������������������������������������������������������������������������������������������������� 47
Access Modifiers���������������������������������������������������������������������������������������������������������������������������������� 49
Properties and Methods����������������������������������������������������������������������������������������������������������������������� 49
Class Heritage�������������������������������������������������������������������������������������������������������������������������������������� 51
Abstract Classes����������������������������������������������������������������������������������������������������������������������������������� 53
Scope���������������������������������������������������������������������������������������������������������������������������������������������������� 54
Type Information����������������������������������������������������������������������������������������������������������������������������������� 56

Generics������������������������������������������������������������������������������������������������������������������������� 58
Generic Functions��������������������������������������������������������������������������������������������������������������������������������� 58
Generic Interfaces�������������������������������������������������������������������������������������������������������������������������������� 59
Generic Classes������������������������������������������������������������������������������������������������������������������������������������ 60
Type Constraints����������������������������������������������������������������������������������������������������������������������������������� 61

vi
■ Contents

TypeScript Futures��������������������������������������������������������������������������������������������������������� 61
Summary������������������������������������������������������������������������������������������������������������������������ 62
Key Points���������������������������������������������������������������������������������������������������������������������� 62

■Chapter 2: Code Organization������������������������������������������������������������������������������ 63
Namespaces������������������������������������������������������������������������������������������������������������������� 64
Modules�������������������������������������������������������������������������������������������������������������������������� 68
Module Re-Exporting���������������������������������������������������������������������������������������������������������������������������� 70
Default Exports������������������������������������������������������������������������������������������������������������������������������������� 70
Exports Object�������������������������������������������������������������������������������������������������������������������������������������� 71
Module Loading������������������������������������������������������������������������������������������������������������������������������������ 71

Mixing Namespace and Modules����������������������������������������������������������������������������������� 73


Packaging����������������������������������������������������������������������������������������������������������������������� 74
Decorators���������������������������������������������������������������������������������������������������������������������� 76
Configurable Decorators����������������������������������������������������������������������������������������������������������������������� 78
Class Decorators����������������������������������������������������������������������������������������������������������������������������������� 79
Property Decorators������������������������������������������������������������������������������������������������������������������������������ 80

Summary������������������������������������������������������������������������������������������������������������������������ 81
Key Points���������������������������������������������������������������������������������������������������������������������� 82

■Chapter 3: The Type System�������������������������������������������������������������������������������� 83
Type Systems����������������������������������������������������������������������������������������������������������������� 83
Optional Static Types������������������������������������������������������������������������������������������������������ 84
Structural Typing������������������������������������������������������������������������������������������������������������ 86
Type Erasure������������������������������������������������������������������������������������������������������������������� 88
Type Inference���������������������������������������������������������������������������������������������������������������� 89
Best Common Type������������������������������������������������������������������������������������������������������������������������������� 90
Contextual Types����������������������������������������������������������������������������������������������������������������������������������� 91
Widened Types�������������������������������������������������������������������������������������������������������������������������������������� 91
When to Annotate��������������������������������������������������������������������������������������������������������������������������������� 91

Duplicate Identifiers������������������������������������������������������������������������������������������������������� 92
Type Checking���������������������������������������������������������������������������������������������������������������� 93
vii
■ Contents

Ambient Declarations����������������������������������������������������������������������������������������������������� 95
Declaration Files����������������������������������������������������������������������������������������������������������������������������������� 96
Definitely Typed������������������������������������������������������������������������������������������������������������������������������������ 97

Summary������������������������������������������������������������������������������������������������������������������������ 97
Key Points���������������������������������������������������������������������������������������������������������������������� 97

■Chapter 4: Object Orientation in TypeScript�������������������������������������������������������� 99
Object Orientation in TypeScript����������������������������������������������������������������������������������� 100
Open Recursion���������������������������������������������������������������������������������������������������������������������������������� 100
Encapsulation������������������������������������������������������������������������������������������������������������������������������������� 102
Delegation������������������������������������������������������������������������������������������������������������������������������������������ 104
Polymorphism������������������������������������������������������������������������������������������������������������������������������������� 106

SOLID Principles����������������������������������������������������������������������������������������������������������� 108


The Single Responsibility Principle (SRP)������������������������������������������������������������������������������������������� 109
The Open–Closed Principle (OCP)������������������������������������������������������������������������������������������������������� 110
The Liskov Substitution Principle (LSP)���������������������������������������������������������������������������������������������� 111
The Interface Segregation Principle (ISP) ������������������������������������������������������������������������������������������ 112
The Dependency Inversion Principle (DIP)������������������������������������������������������������������������������������������ 114

Design Patterns������������������������������������������������������������������������������������������������������������ 115


The Strategy Pattern��������������������������������������������������������������������������������������������������������������������������� 116
The Abstract Factory Pattern�������������������������������������������������������������������������������������������������������������� 116
Practical Example������������������������������������������������������������������������������������������������������������������������������� 117

Mixins��������������������������������������������������������������������������������������������������������������������������� 121
TypeScript Mixins������������������������������������������������������������������������������������������������������������������������������� 121
When to Use Mixins���������������������������������������������������������������������������������������������������������������������������� 123
Restrictions����������������������������������������������������������������������������������������������������������������������������������������� 123
Real Mixins����������������������������������������������������������������������������������������������������������������������������������������� 125

Summary���������������������������������������������������������������������������������������������������������������������� 126
Key Points�������������������������������������������������������������������������������������������������������������������� 127

viii
■ Contents


■Chapter 5: Understanding the Runtime������������������������������������������������������������� 129
Runtime Features��������������������������������������������������������������������������������������������������������� 129
Scope��������������������������������������������������������������������������������������������������������������������������� 131
Callbacks�������������������������������������������������������������������������������������������������������������������������������������������� 134
Passing Functions as Arguments������������������������������������������������������������������������������������������������������� 137
Promises��������������������������������������������������������������������������������������������������������������������������������������������� 138

Events��������������������������������������������������������������������������������������������������������������������������� 147
TypeScript’s Custom-Event Mechanism��������������������������������������������������������������������������������������������� 149
Event Phases�������������������������������������������������������������������������������������������������������������������������������������� 151

Extending Objects�������������������������������������������������������������������������������������������������������� 151


Extending the Prototype��������������������������������������������������������������������������������������������������������������������� 152
Sealing Objects����������������������������������������������������������������������������������������������������������������������������������� 154
Alternatives to Extending�������������������������������������������������������������������������������������������������������������������� 155

Summary���������������������������������������������������������������������������������������������������������������������� 156
Key Points�������������������������������������������������������������������������������������������������������������������� 157

■Chapter 6: Running TypeScript in a Browser����������������������������������������������������� 159
The Anatomy of a Web Browser����������������������������������������������������������������������������������� 159
Reflows and Frames Per Second�������������������������������������������������������������������������������������������������������� 160
The Interesting Components��������������������������������������������������������������������������������������������������������������� 162

The Document Object Model���������������������������������������������������������������������������������������� 164


Finding Elements�������������������������������������������������������������������������������������������������������������������������������� 165
Changing Elements����������������������������������������������������������������������������������������������������������������������������� 166
Events������������������������������������������������������������������������������������������������������������������������������������������������� 167
Frameworks and Libraries������������������������������������������������������������������������������������������������������������������ 169

Network������������������������������������������������������������������������������������������������������������������������ 170
AJAX��������������������������������������������������������������������������������������������������������������������������������������������������� 170
WebSockets���������������������������������������������������������������������������������������������������������������������������������������� 173
Real-Time Communications��������������������������������������������������������������������������������������������������������������� 173

ix
■ Contents

Storage������������������������������������������������������������������������������������������������������������������������� 174
Session Storage���������������������������������������������������������������������������������������������������������������������������������� 174
Local Storage�������������������������������������������������������������������������������������������������������������������������������������� 175
Storage Restrictions��������������������������������������������������������������������������������������������������������������������������� 176
IndexedDB������������������������������������������������������������������������������������������������������������������������������������������ 176
Storage Roundup�������������������������������������������������������������������������������������������������������������������������������� 183
Geolocation������������������������������������������������������������������������������������������������������������������ 183
Sensors������������������������������������������������������������������������������������������������������������������������ 185
Battery Status������������������������������������������������������������������������������������������������������������������������������������� 185
Proximity Sensor�������������������������������������������������������������������������������������������������������������������������������� 187
Light Sensor��������������������������������������������������������������������������������������������������������������������������������������� 188
Motion and Orientation����������������������������������������������������������������������������������������������������������������������� 188
Other Device Sensors������������������������������������������������������������������������������������������������������������������������� 189
Sensor Roundup��������������������������������������������������������������������������������������������������������������������������������� 189
Web Workers���������������������������������������������������������������������������������������������������������������� 190
Packaging Your Program���������������������������������������������������������������������������������������������� 192
Summary���������������������������������������������������������������������������������������������������������������������� 192
Key Points�������������������������������������������������������������������������������������������������������������������� 192

■Chapter 7: Running TypeScript on a Server������������������������������������������������������� 195
Install Node������������������������������������������������������������������������������������������������������������������ 195
Creating a New Project������������������������������������������������������������������������������������������������� 196
NPM������������������������������������������������������������������������������������������������������������������������������ 196
Simple Node Program�������������������������������������������������������������������������������������������������� 199
Request Information����������������������������������������������������������������������������������������������������� 200
Using Express to Write Applications����������������������������������������������������������������������������� 201
Simple Express Program�������������������������������������������������������������������������������������������������������������������� 202
Multiple Routes����������������������������������������������������������������������������������������������������������������������������������� 203
Handling Errors����������������������������������������������������������������������������������������������������������������������������������� 203
Express Book Project�������������������������������������������������������������������������������������������������������������������������� 205
Summary���������������������������������������������������������������������������������������������������������������������� 216
Key Points�������������������������������������������������������������������������������������������������������������������� 216
x
■ Contents


■Chapter 8: Exceptions, Memory, and Performance�������������������������������������������� 217
Exceptions�������������������������������������������������������������������������������������������������������������������� 217
Throwing Exceptions�������������������������������������������������������������������������������������������������������������������������� 218
Exception Handling����������������������������������������������������������������������������������������������������������������������������� 219

Memory������������������������������������������������������������������������������������������������������������������������ 224
Releasing Resources�������������������������������������������������������������������������������������������������������������������������� 224
Garbage Collection����������������������������������������������������������������������������������������������������������������������������� 225
Performance����������������������������������������������������������������������������������������������������������������� 228
Summary���������������������������������������������������������������������������������������������������������������������� 232
Key Points�������������������������������������������������������������������������������������������������������������������� 232

■Chapter 9: Using JavaScript Libraries��������������������������������������������������������������� 233
Creating Type Definitions���������������������������������������������������������������������������������������������� 234
Creating a TypeScript Application with Knockout������������������������������������������������������������������������������� 235
Silencing the Compiler����������������������������������������������������������������������������������������������������������������������� 237
Iteratively Improving Type Definitions������������������������������������������������������������������������������������������������� 238

Converting a JavaScript Application����������������������������������������������������������������������������� 241


Summary���������������������������������������������������������������������������������������������������������������������� 243
Key Points�������������������������������������������������������������������������������������������������������������������� 243

■Chapter 10: Automated Testing������������������������������������������������������������������������� 245
Framework Choices����������������������������������������������������������������������������������������������������� 246
Testing with Jest���������������������������������������������������������������������������������������������������������� 246
Installing Jest������������������������������������������������������������������������������������������������������������������������������������� 246
The First Specification������������������������������������������������������������������������������������������������������������������������ 247
Driving the Implementation���������������������������������������������������������������������������������������������������������������� 248
Refactoring����������������������������������������������������������������������������������������������������������������������������������������� 251
Isolating Dependencies���������������������������������������������������������������������������������������������������������������������� 254

Summary���������������������������������������������������������������������������������������������������������������������� 255
Key Points�������������������������������������������������������������������������������������������������������������������� 256

xi
■ Contents


■Appendix 1: JavaScript Quick Reference���������������������������������������������������������� 257
Variables����������������������������������������������������������������������������������������������������������������������� 257
Functions���������������������������������������������������������������������������������������������������������������������� 258
Conditional Statements������������������������������������������������������������������������������������������������ 259
Loops���������������������������������������������������������������������������������������������������������������������������� 260
Strings�������������������������������������������������������������������������������������������������������������������������� 261
Promises���������������������������������������������������������������������������������������������������������������������� 262
Summary���������������������������������������������������������������������������������������������������������������������� 263

■Appendix 2: TypeScript Compiler���������������������������������������������������������������������� 265
Getting Help������������������������������������������������������������������������������������������������������������������ 265
Sample File������������������������������������������������������������������������������������������������������������������ 265
Common Flags������������������������������������������������������������������������������������������������������������� 266
Module Kind���������������������������������������������������������������������������������������������������������������������������������������� 266
ECMAScript Target Version����������������������������������������������������������������������������������������������������������������� 268
Generate Declarations������������������������������������������������������������������������������������������������������������������������ 269
Remove Comments����������������������������������������������������������������������������������������������������������������������������� 269
Combined Output�������������������������������������������������������������������������������������������������������������������������������� 269

Code Quality Flags�������������������������������������������������������������������������������������������������������� 269


Defaults���������������������������������������������������������������������������������������������������������������������������������������������� 270
Strict Switch��������������������������������������������������������������������������������������������������������������������������������������� 270
Catch Accidental Fallthroughs������������������������������������������������������������������������������������������������������������ 270
Catch Missing Return Statements������������������������������������������������������������������������������������������������������ 271
Unused Local Variables����������������������������������������������������������������������������������������������������������������������� 271
Unused Parameters���������������������������������������������������������������������������������������������������������������������������� 272

JavaScript Compilation������������������������������������������������������������������������������������������������ 272


Allow JavaScript��������������������������������������������������������������������������������������������������������������������������������� 272
Check JavaScript�������������������������������������������������������������������������������������������������������������������������������� 272

xii
■ Contents


■Appendix 3: Bitwise Flags��������������������������������������������������������������������������������� 273
Bit Flags Explained������������������������������������������������������������������������������������������������������� 274
Bitwise Operations������������������������������������������������������������������������������������������������������� 274

■Appendix 4: Coding Katas��������������������������������������������������������������������������������� 277
Performing a Kata�������������������������������������������������������������������������������������������������������� 278
Example: The Fizz Buzz Kata���������������������������������������������������������������������������������������� 279
Common Coding Kata Rules����������������������������������������������������������������������������������������� 279
Summary���������������������������������������������������������������������������������������������������������������������� 280

Index��������������������������������������������������������������������������������������������������������������������� 281

xiii
About the Author

Steve Fenton is the Principal Developer at Profound Works. He has been


sharing his passion for TypeScript since October 2012, presenting at
developer meet-ups, running training sessions, and answering questions
on Stack Overflow. He has worked on large-scale JavaScript applications
for over 14 years, and with TypeScript for over 5 years. In his spare time, he
writes unit-testing frameworks, behavior-driven development frameworks,
and web crawlers. He lives in Basingstoke, United Kingdom, with his
wife Rebecca and daughter Lily, and enjoys studying psychology and
philosophy.

xv
Acknowledgments

A book is enjoyable when you work with the right people, and those people are Gwenan Spearing at Apress
and my smart technical reviewers Rich O’Kelly, Martin Milsom, Dan Horrocks-Burgess, and Jamie Wright.
I am incredibly grateful to Nancy Chen for being so patient with my sporadic writing habits, last-minute
changes, and vague estimates.
This second edition would not have been possible without the contributions of all the smart people that
helped create the first book; Mark Jones, Mark Rendle, Basarat Ali Syed, Christine Ricketts, Boris Yankov,
Diullei Gomes, Masahiro Wakame, Jason Jarrett, Bart van der Schoor, John Reilly, Igor Oleinikov, Luke
Hoban, Jonathan Turner, and of course - Ryan Cavanaugh.
I am also grateful to all of my amazing colleagues, past and present, who inspire me to keep learning
and growing.

xvii
Introduction

Atwood’s Law: any application that can be written in JavaScript will eventually be written
in JavaScript.
—Jeff Atwood

TypeScript is a language created and maintained by Microsoft, and released under an open-source Apache
2.0 License (2004). The language is focused on making the development of JavaScript programs scale to
many thousands of lines of code. In fact, Microsoft has written both the Azure Management Portal (1.2
million lines of code) and the Visual Studio Code editor (300,000 lines of code) in TypeScript. The language
attacks the large-scale JavaScript programming problem by offering better design-time tooling, compile-
time checking, and dynamic module loading at runtime.
As you might expect from a language created by Microsoft, there is excellent support for TypeScript
within Visual Studio, but plenty of other development tools have also added support for the language,
including VS Code, WebStorm, Eclipse, Sublime Text, Vi, Atom, IntelliJ, and Emacs among others. The
widespread support from these tools as well as the permissive open-source license makes TypeScript a
viable option outside of the traditional Microsoft ecosystem.
The TypeScript language is a typed superset of JavaScript, which is compiled to plain JavaScript in
the flavor of your choosing. This makes programs written in TypeScript highly portable as they can run
on almost any machine — in web browsers, on web servers, and even in native applications on operating
systems that expose a JavaScript API, such as WinJS.
The language features found in TypeScript can be divided into three categories based on their
relationship to JavaScript (see Figure 1). The first two sets are related to versions of the ECMA-262
ECMAScript Language Specification, which is the official specification for JavaScript. The ECMAScript 5
specification forms the basis of TypeScript and supplies the largest number of features in the language.
Subsequent versions of the ECMAScript specification are rolled into TypeScript releases, often as early
previews that feature down-level compilation to older versions of the specication. The third and final set of
language features includes items that are not planned to become part of the ECMAScript standard, such as
generics and type annotations. All the additional features of TypeScript can be output to a number of widely
supported versions of JavaScript.
TypeScript has several native frameworks, including Angular, Ionic, RxJs 5, and Dojo 2. Additionally,
because TypeScript is such a close relative of JavaScript, you can consume the myriad of existing libraries
and frameworks written in JavaScript; Aurelia, Backbone, Bootstrap, Durandal, jQuery, Knockout,
Modernizr, PhoneGap, Prototype, Raphael, React, Underscore, Vue, and many more are all usable in
TypeScript programs. Correspondingly, once your TypeScript program has been compiled it can be
consumed from any JavaScript program too.
TypeScript's similarity to JavaScript is beneficial if you already have experience with JavaScript or other
C-like languages. The similarity also aids the debugging process as the generated JavaScript correlates
closely to the original TypeScript code. Source maps can also be generated to aid debugging, with browser
developer tools displaying your TypeScript code during in-browser debugging.

xix
■ Introduction

Figure 1. TypeScript language feature sources

If you still need to be convinced about using TypeScript or need help convincing others, I summarize
the benefits of the language as well as the problems it can solve in the following sections. I also include an
introduction to the components of TypeScript and some of the alternatives. If you would rather get started
with the language straight away, you can skip straight to Chapter 1.

Who This Book Is For


This book is for programmers and architects working on large-scale JavaScript programs, either running in
a browser, on a server, or on an operating system that exposes a JavaScript API. Previous experience with
JavaScript or another C-like language is useful when reading this book, as well as a working knowledge of
object orientation and design patterns, although I'll cover some aspects of this in detail later.

Structure
This book is organized into ten chapters and four appendices.
Chapter 1: TypeScript Language Features: describes the language features in
detail, from simple type annotations to important structural elements, with
stand-alone examples of how to use each one.
Chapter 2: Code Organization: clarifies how code can be organized, loaded, and
packaged with a view to growing your program to millions of lines of code.
Chapter 3: The Type System: explains the details of working within TypeScript's
structural type system and describes the details on type erasure, type inference,
and ambient declarations.

xx
■ Introduction

Chapter 4: Object Orientation in TypeScript: introduces the important elements


of object orientation and contains examples of design patterns and SOLID
principles in TypeScript. This chapter also introduces the concept of mixins with
practical examples.
Chapter 5: Understanding the Runtime: describes the impact of scope, callbacks,
events, and extensions on your program.
Chapter 6: Running TypeScript in a Browser: a thorough walkthrough including
working with the Document Object Model, AJAX, session and local storage,
IndexedDB, geolocation, hardware sensors, and web workers as well as
information on packaging your program for the Web.
Chapter 7: Running TypeScript on a Server: an explanation of running programs
on a JavaScript server with examples for Node and a basic end-to-end example
application written in Express and Mongoose.
Chapter 8: Exceptions, Memory, and Performance: describes exceptions and
exception handling with information on memory management and garbage
collection. It includes a simple performance testing utility to exercise and
measure your program.
Chapter 9: Using JavaScript Libraries: explains how to consume any of the
millions of JavaScript libraries from within your TypeScript program, including
information on how to create your own type definitions and how to migrate your
JavaScript program to TypeScript.
Chapter 10: Automated Testing: a walkthrough of automated testing in your
TypeScript program with examples written using the Jest framework.
Appendix 1: JavaScript Quick Reference: an introduction to the essential
JavaScript features for anyone who needs to brush up on their JavaScript before
diving into TypeScript.
Appendix 2: TypeScript Compiler: explains how to use the compiler on the
command line and describes many of the flags you can pass to customize your
build.
Appendix 3: Bitwise Flags: dives into the details of bitwise flags including
the low-level details of how they work as well as examples using TypeScript
enumerations.
Appendix 4: Coding Katas: introduces the concept of coding katas and provides
an example for you to try, along with techniques you can use to make katas more
effective.

The TypeScript Components


TypeScript is made up of three distinct but complementary parts, which are shown in Figure 2.

xxi
■ Introduction

Figure 2. The TypeScript components

The language consists of the new syntax, keywords, and type annotations. As a programmer, the
language will be the component you will become most familiar with. Understanding how to supply type
information is an important foundation for the other components because the compiler and language
service are most effective when they understand the complex structures you use within your program.
The compiler performs the type erasure and code transformations that convert your TypeScript code
into JavaScript. It will emit warnings and errors if it detects problems and can perform additional tasks such
as combining the output into a single file, generating source maps, and more.
The language service provides type information that can be used by development tools to supply
autocompletion, type hinting, refactoring options, and other creative features based on the type information
that has been gathered from your program.

Compile or Transpile?
The term transpiling has been around since the last century, but there is some confusion about its meaning.
In particular, there has been some confusion between the terms compilation and transpilation. Compilation
describes the process of taking source code written in one language and converting it into another language.
Transpilation is a specific kind of compilation and describes the process of taking source code written in one
language and transforming it into another language with a similar level of abstraction. So, you might compile
a high-level language into an assembly language, but you would transpile TypeScript to JavaScript as they
are similarly abstracted.
Other common examples of transpilation include C++ to C, CoffeeScript to JavaScript, Dart to
JavaScript, and PHP to C++.

Which Problems Does TypeScript Solve?


Since its first beta release in 1995, JavaScript (or LiveScript as it was known at the time it was released) has
spread like wildfire. Nearly every computer in the world has a JavaScript interpreter installed. Although it
is perceived as a browser-based scripting language, JavaScript has been running on web servers since its
inception, supported on Netscape Enterprise Server, IIS (since 1996), and on Node since 2011. JavaScript can
even be used to write native applications on operating systems such as Windows.

xxii
■ Introduction

Despite its popularity, it hasn't received much respect from developers — possibly because it contains
many snares and traps that can entangle a large program much like the tar pit pulling the mammoth to
its death, as described by Fred Brooks (1975). If you are a professional programmer working with large
applications written in JavaScript, you will almost certainly have rubbed up against problems once your
program chalked up a few thousand lines. You may have experienced naming conflicts, substandard
programming tools, complex modularization, unfamiliar prototypal inheritance that makes it hard to reuse
common design patterns easily, and difficulty keeping a readable and maintainable code base. TypeScript
solves problems such as these.
Because JavaScript has a C-like syntax, it looks familiar to most programmers. This is one of JavaScript's
key strengths, but it is also the cause of many surprises, especially in the following areas:
• Prototypal inheritance
• Equality and type juggling
• Management of modules
• Scope
• Lack of types
Typescript solves or eases these problems in several ways. Each of these topics is discussed in this
introduction.

Prototypal Inheritance
Prototype-based programming is a style of object-oriented programming that is mainly found in interpreted
dynamic languages. It was first used in a language called Self, created by David Ungar and Randall Smith in
1986, but it has been used in a selection of languages since then. Of these prototypal languages, JavaScript
is by far the most widely known, although this has done little to bring prototypal inheritance into the
mainstream. Despite its validity, prototype-based programming is somewhat esoteric; class-based object
orientation is far more commonplace and will be familiar to most programmers.
TypeScript solves this problem by adding classes, namespaces, modules, and interfaces. This allows
programmers to transfer their existing knowledge of objects and code structure from other languages,
including implementing interfaces, inheritance, and code organization. Classes and modules are an early
preview of JavaScript proposals and because TypeScript can compile to earlier versions of JavaScript, it
allows you to use these features independent of support for the newer ECMAScript specifications. All these
features are described in detail in Chapter 1.

Equality and Type Juggling


JavaScript has always supported dynamically typed variables, and as a result it expends effort at runtime
working out types and coercing them into other types on the fly to make statements work that in a statically
typed language would cause an error.
The most common type coercions involve strings, numbers, and Boolean target types. Whenever
you attempt to concatenate a value with a string, the value will be converted to a string, if you perform a
mathematical operation an attempt will be made to turn the value into a number, and if you use any value
in a logical operation there are special rules that determine whether the result will be true or false. When an
automatic type conversion occurs, it is commonly referred to as type juggling.
In some cases, type juggling can be a useful feature, in particular in creating shorthand logical
expressions. In other cases, type juggling hides an accidental use of different types and causes unintended
behavior as discussed in Chapter 1. A common JavaScript example is shown in Listing 1.

xxiii
■ Introduction

Listing 1. Type juggling


const num = 1;
const str = '0';

// result is '10' not 1


const strTen = num + str;

// result is 20
const result = strTen * 2;

TypeScript gracefully solves this problem by introducing type checking, which can provide warnings
at design and compile time to pick up potential unintended juggling. Even in cases where it allows implicit
type coercion, the result will be assigned the correct type. This prevents dangerous assumptions from going
undetected. This feature is covered in detail in Chapter 3.
The introduction of types in TypeScript does not preclude the use of dynamic types. You can choose
when to use types, and when to go without them. TypeScript does not force you to do anything, it is just
there to help.

Management of Modules
If you have worked with JavaScript, it is likely that you will have come across a dependency problem. Some
of the common problems include the following:
• Forgetting to add a script tag to a web page
• Adding scripts to a web page in the wrong order
• Finding out you have added scripts that aren't used
There is also a series of issues you may have come across if you are using tools to combine your scripts
into a single file to reduce network requests or if you minify your scripts to lower bandwidth usage.
• Combining scripts into a single script in the wrong order
• Finding out that your chosen minification tool doesn't understand single-line
comments
• Trying to debug combined and minified scripts
You may have already solved some of these issues using module loading, as the pattern is gaining
traction in the JavaScript community. However, TypeScript makes module loaders the default way of
working and allows your modules to be compiled to suit the most prevalent module loading styles without
requiring changes to your code. The details of module loading in web browsers are covered in Chapter 6 and
on the server in Chapter 7.

Scope
In most modern C-like languages, the curly braces create a new context for scope. A variable declared inside a
set of curly braces cannot be seen outside of that block. JavaScript has bucked this trend traditionally by being
functionally scoped, which means blocks defined by curly braces have no effect on scope. Instead, variables are
scoped to the function they are declared in, or the global scope if they are not declared within a function. There
can be further complications caused by the accidental omission of the var keyword within a function, thus
promoting the variable into the global scope. More complications are caused by variable hoisting, resulting in
all variables within a function behaving as if they were declared at the top of the function.
xxiv
■ Introduction

The introduction of the const and let variable declarations have gone some way to solving this
problem, and if you are starting from a clean sheet you can avoid the older var variable declaration
altogether.
Despite some tricky surprises with scope, JavaScript does provide a powerful mechanism that wraps
the current lexical scope around a function declaration to keep values to hand when the function is later
executed. These closures are one of the most powerful features in JavaScript.
TypeScript eases scope problems by warning you about implicit global variables, provided you avoid
adding variables to the global scope. This safety net is demonstrated in Listing 2.

Listing 2. Accidental global scope error


function process() {
    // Error! Cannot find name 'accidentalGlobal;
    accidentalGlobal = 5;
}

Lack of Types
The problem with JavaScript isn't that it has no types, because each variable does have a type; it is just that
the type can be changed by each assignment. A variable may start off as a string, but an assignment can
change it to a number, an object, or even a function. The real problem here is that the development tools
cannot be improved beyond a reasonable guess about the type of a variable. If the development tools don’t
know the types, the autocompletion and type hinting is often too general to be useful.
By formalizing type information, TypeScript allows development tools to supply specific contextual
help that otherwise would not be possible.

Which Problems Are Not Solved?

TypeScript is not a crutch any more than JSLint is a crutch. It doesn’t hide JavaScript (as
CoffeeScript tends to do).
—Ward Bell

TypeScript remains largely faithful to JavaScript. The TypeScript specification adds many language features,
but it doesn't attempt to change the ultimate style and behavior of the JavaScript language. It is just as
important for TypeScript programmers to embrace the idiosyncrasies of the runtime as it is for JavaScript
programmers. The aim of the TypeScript language is to make large-scale JavaScript programs manageable
and maintainable. No attempt has been made to twist JavaScript development into the style of C#, Java,
Ruby, Python, or any other language (although it has taken inspiration from many languages).

Prerequisites
To benefit from the features of TypeScript, you'll need access to an integrated development environment that
supports the syntax and compiler. The examples in this book were written using Visual Studio 2017, but you
can use VS Code, WebStorm/PHPStorm, Eclipse, Sublime Text, Vi, Emacs, or any other development tools
that support the language; you can even try many of the simpler examples on the TypeScript Playground
provided by Microsoft. I often use the TypeScript Playground when answering questions on the language.

xxv
■ Introduction

From the Visual Studio 2013 Spring Update (Update 2), TypeScript is a first-class language in Visual
Studio. Prior to this, an additional extension needed to be installed. Although the examples in this book are
shown in Visual Studio, you can use any of the development tools that were listed above. In particular, Visual
Studio Code is a free cross-platform editor with native TypeScript support - so you can write your TypeScript
code on any machine you have on hand, regardless of the operating system.
It is also worth downloading and installing Node (which is required to follow many of the examples) as
it will allow you to access the Node Package Manager and the thousands of modules and utilities available
through it. For example, you can use task runners such as Grunt and Gulp to watch your TypeScript files and
compile them automatically each time you change them if your development tools don't do this for you.
Node is free and can be downloaded for multiple platforms from the official Node website.
https://nodejs.org/
To avoid being greatly sidetracked, I have avoided using any task runners to perform additional
operations outside of Visual Studio, but once you have mastered TypeScript you will almost certainly want
to add a task runner, such as Gulp or Grunt, to your development workflow. I have referenced some web
dependencies from the node_modules folder in the examples in this book; but on a real-world project I
would use a task runner to lift and shift the website dependencies into a different folder that I would be
happy to deploy to a web server. The node_modules folder often contains a great deal of files that I would not
deploy to a web server.

TypeScript Alternatives
TypeScript is not the only alternative to writing to plain JavaScript.
The strongest TypeScript alternative is Babel, a compiler that exposes the latest ECMAScript features
with plugins for down-level compilation and polyfills to make your program work in current browsers. The
aim of the Babel project is to make the latest features available much sooner than they otherwise would be,
but Babel doesn't introduce compile-time type checking. Babel also features in many TypeScript workflows,
where Babel is executed after the TypeScript compiler, rather than using TypeScript to perform the down-
level compilation. You can read about Babel on the official website:
https://babeljs.io/
For a number of years, CoffeeScript was a popular alternative with a terse syntax that compiles to
sensible JavaScript code. CoffeeScript doesn't offer many of the additional features that TypeScript offers,
such as static type checking. It is also a very different language to JavaScript, which means you need to
translate snippets of code you find online into CoffeeScript to use them. In 2017, however, CoffeeScript
reached the top three "most dreaded languages" in the Stack Overflow developer survey (next to VBA, and
Visual Basic 6). In the same survey, TypeScript landed in the top three most loved languages. You can find
out more about CoffeeScript on the official website:
http://coffeescript.org/
Another alternative is Google's Dart language. Dart has much in common with TypeScript. It is class-
based, object oriented, and offers optional types that can be checked by a static checker. Dart was originally
conceived as a replacement for JavaScript, and was only intended to be compiled to JavaScript to provide
wide support in the short term while native support for Dart was added to browsers.
It seems unlikely at this stage that Dart will get the kind of browser support that JavaScript has won,
so the compile-to-JavaScript mechanism will likely remain core to Dart's future in the web browser. The
decision by Google to adopt TypeScript for the Angular project may be indicative of their commitment to
Dart, although it is still described as a long-term project. You can read about Dart on the official website for
the language:
https://www.dartlang.org/

xxvi
■ Introduction

There are also converters that will compile from most languages to JavaScript, including C#, Ruby, Java,
and Haskell. These may appeal to programmers who are uncomfortable stepping outside of their primary
programming language.
It is also worth bearing in mind that for small applications and web page widgets, you can defer the
decision and write the code in plain JavaScript. With TypeScript in particular, there is no penalty for starting
in JavaScript as you can simply paste your JavaScript code into a TypeScript file later on to make the switch.
Equally, there is little penalty for writing small programs in TypeScript, especially if you already have a
workflow in place to generate combined or minified files each time you save your application.

Summary
TypeScript is an application-scale programming language that provides early access to proposed new
JavaScript features and powerful additional features like static type checking. You can write TypeScript
programs to run in web browsers or on servers and you can reuse code between browser and server
applications.
TypeScript solves many problems in JavaScript, but it respects the patterns and implementation of the
underlying JavaScript language, for example, the ability to have dynamic types.
You can use many integrated development environments with TypeScript, with several providing first-
class support including type checking and autocompletion that will improve your productivity and help
eliminate mistakes at design time.

Key Points
• TypeScript is a language, a compiler, and a language service.
• You can paste existing JavaScript into your TypeScript program.
• Compiling from TypeScript to JavaScript is known specifically as transpiling.
• TypeScript is not the only alternative way of writing JavaScript, but it has gained
incredible traction in its first five years.

xxvii
CHAPTER 1

TypeScript Language Features

What if we could strengthen JavaScript with the things that are missing for large scale
application development, like static typing, classes [and] modules... that’s what TypeScript
is about.
—Anders Hejlsberg

TypeScript is a superset of JavaScript. That means that the TypeScript language includes the entire JavaScript
language plus a collection of useful additional features. This contrasts with the various subsets of JavaScript
and the various linting tools that seek to reduce the available features to create a smaller language with
fewer surprises. This chapter will introduce you to the extra language features, starting with simple type
annotations and progressing to more advanced features and structural elements of TypeScript. This chapter
doesn’t cover every feature included in the ECMAScript language specification, so if you need a refresher on
JavaScript, take a look at Appendix 1.
One important thing to remember is that all the standard control structures found in JavaScript are
immediately available within a TypeScript program. This includes the following:
• Control flows
• Data types
• Operators
• Subroutines
The basic building blocks of your program will come from JavaScript, including if statements, switch
statements, loops, arithmetic, logical tests, and functions. This is one of the key strengths of TypeScript — it
is based on a language (and a family of languages) that is already familiar to a vast and varied collection
of programmers. JavaScript is thoroughly documented not only in the ECMA-262 specification, but also in
books, on developer network portals, forums, and question-and-answer websites. When features are added
to JavaScript, they will also appear in TypeScript.
The TypeScript compiler is typically updated with new JavaScript features early in their specification.
Most of the features are available before browsers support them. In many cases, you can use the features in
your TypeScript program as the compiler will convert them into code that targets the older versions of the
ECMAScript standard.
Each of the language features discussed in this chapter has short, self-contained code examples that put
the feature in context. For the purposes of introducing and explaining features, the examples are short and
to the point; this allows the chapter to be read end to end. However, this also means you can refer back to the
chapter as a reference later on. Once you have read this chapter, you should know everything you will need
to understand the more complex examples described throughout the rest of the book.

© Steve Fenton 2018 1


S. Fenton, Pro TypeScript, https://doi.org/10.1007/978-1-4842-3249-1_1
Chapter 1 ■ TypeScript Language Features

JavaScript Is Valid TypeScript


Before we find out more about the TypeScript syntax, it is worth stressing one important fact: All JavaScript
is valid TypeScript. You don’t need to discard any of your JavaScript know-how as it can all be transferred
directly to your TypeScript code. You can take existing JavaScript code, add it to a TypeScript file, and all the
statements will be valid. There is a subtle difference between valid code and error-free code in TypeScript;
because, although your code may work, the TypeScript compiler will warn you about any potential problems
it has detected. Finding subtle and previously undetected bugs is a common story shared by programmers
making the transition to TypeScript.
If you transfer a JavaScript listing into a TypeScript file, you may receive errors or warnings even though
the code is considered valid. A common example comes from the dynamic type system in JavaScript wherein
it is perfectly acceptable to assign values of different types to the same variable during its lifetime. TypeScript
detects these assignments and generates errors to warn you that the type of the variable has been changed
by the assignment. Because this is a common cause of errors in a program, you can correct the error by
creating separate variables, by performing a type assertion, or by making the variable dynamic. There is
further information on type annotations later in this chapter, and the type system is discussed in detail in
Chapter 3.
Unlike some compilers that will only create output where no compilation errors are detected, the
TypeScript compiler will still attempt to generate sensible JavaScript code. The TypeScript code shown in
Listing 1-1 generates an error, but the JavaScript output is still produced. This is an admirable feature, but
as always with compiler warnings and errors, you should correct the problem in your source code and get a
clean compilation. If you routinely ignore these messages, your program will eventually exhibit unexpected
behavior. In some cases, your listing may contain errors that are so severe that the TypeScript compiler won’t
be able to generate the JavaScript output.

■■Caution The only exceptions to the “all JavaScript is valid TypeScript” rule are the with statement and
vendor-specific extensions, until they are formally added to the ECMAScript specification. You could technically
still use the with statement, but all statements within the block would be unchecked.

The JavaScript with statement in Listing 1-1 shows two examples of the same routine. Although the
first calls Math.PI explicitly, the second uses a with statement, which adds the properties and functions of
Math to the current scope. Statements nested inside the with statement can omit the Math prefix and call
properties and functions directly, for example, the PI property or the floor function.
At the end of the with statement, the original lexical scope is restored, so subsequent calls outside of the
with block must use the Math prefix.

Listing 1-1. Using JavaScript’s “with” statement


// Not using with
const radius1 = 4;
const area1 = Math.PI * radius1 * radius1;

// Using with
const radius2 = 4;
with (Math) {
    const area2 = PI * radius2 * radius2;
}

2
Chapter 1 ■ TypeScript Language Features

The with statement was not allowed in strict mode in ECMAScript 5 and later versions of ECMAScript
use strict mode by default for classes and modules. TypeScript treats with statements as an error and will
treat all types within the with statement as dynamic types. This is due to the following:
• The fact it is disallowed in strict mode.
• The general opinion that the with statement is dangerous.
• The practical issues of determining the identifiers that are in scope at compile time.
So, with these minor exceptions to the rule in mind, you can place any valid JavaScript into a TypeScript
file and it will be valid TypeScript. As an example, here is the area calculation script transferred to a
TypeScript file.

■■Note The ECMAScript 6 specification, also known as “ES6 Harmony,” represented a substantial change to
the JavaScript language. The specification has been divided into annual chunks, released as ECMAScript 2015,
ECMAScript 2016, and so on.

Listing 1-2. Transferring JavaScript in to a TypeScript file


const radius = 4;
const area = Math.PI * radius * radius;

In Listing 1-2, the statements are just plain JavaScript, but in TypeScript the variables radius and area
will both benefit from type inference. Because radius is initialized with the value 4, it can be inferred that
the type of radius is number. With just a slight increase in effort, the result of multiplying Math.PI, which is
known to be a number, with the radius variable that has been inferred to be a number, it is possible to infer
the type of area is also a number.
With type inference at work, assignments can be checked for type safety. Figure 1-1 shows how an
unsafe assignment is detected when a string is assigned to the radius variable. There is a more detailed
explanation of type inference in Chapter 3. For now, rest assured that type inference is a good thing, and it
will save you a lot of effort.

Figure 1-1. Static type checking

3
Chapter 1 ■ TypeScript Language Features

Variables
TypeScript variables must follow the JavaScript naming rules. The identifier used to name a variable must
satisfy the following conditions.
The first character must be one of the following:
• an uppercase letter
• a lowercase letter
• an underscore
• a dollar sign
• a Unicode character from categories—Uppercase letter (Lu), Lowercase letter (Ll),
Title case letter (Lt), Modifier letter (Lm), Other letter (Lo), or Letter number (Nl)
Subsequent characters follow the same rule and additionally allow the following:
• numeric digits
• a Unicode character from categories—Non-spacing mark (Mn), Spacing combining
mark (Mc), Decimal digit number (Nd), or Connector punctuation (Pc)
• the Unicode characters U+200C (Zero Width Non-Joiner) and U+200D
(Zero Width Joiner)
You can test a variable identifier for conformance to the naming rules using the JavaScript variable
name validator by Mathias Bynens.

http://mothereff.in/js-variables

■■Note The availability of some of the more exotic characters can allow some interesting identifiers.
You should consider whether this kind of variable name causes more problems than it solves. For example,
this is valid JavaScript: const = 'Dignified';

Variables declared with const or let are block scoped, whereas variables declared with the older var
keyword are function scoped. If you omit these keywords, you are implicitly (and perhaps accidentally)
declaring the variable in the global scope. It is advisable to reduce the number of variables you add to the
global scope, as they are at risk of name collisions. You can avoid the global scope by declaring variables
local to their use, such as within functions, modules, namespaces, classes, or a simple set of curly braces if
you are using the block-scoped keywords.
When you limit the scope of a variable, it means it cannot be manipulated from outside of the scope of
which it was created. The scope follows a nesting rule that allows a variable to be used in the current scope,
and in inner nested scopes – but not outside. In other words, you can use variables declared in the current
scope and variables from wider scopes. See Listing 1-3.

4
Chapter 1 ■ TypeScript Language Features

Listing 1-3. Block scope


let globalScope = 1;

{
    let blockScope = 2;

    // OK. This is from a wider scope


    globalScope = 100;

    // Error! This is outside of the scope the variable is declared in


    nestedBlockScope = 300;

    {
        let nestedBlockScope = 3;

        // OK. This is from a wider scope


        globalScope = 1000;

        // OK. This is from a wider scope


        blockScope = 2000;
    }
}

TypeScript catches scope violations and will warn you when you attempt to access a variable that is
declared in a narrower scope. You can help the compiler to help you by avoiding a valid, but often accidental
coding style of reusing a name in a different scope. In Listing 1-4, the logging statements work correctly, with
both firstName variables being preserved separately. This means the original variable is not overwritten by
the nested variable with the same name.

Listing 1-4. Name reuse with let


let firstName = 'Chris';

{
    let firstName = 'Tudor';

    console.log('Name 1: ' + firstName);


}

console.log('Name 2: ' + firstName);

// Output:
// Name 1: Tudor
// Name 2: Chris

If in place of the let keyword the var keyword had been used, both logging statements would show the
name “Tudor,” as shown in Listing 1-5. Despite both variables appearing to be a separate declaration, only
one variable named firstName exists, and it is overwritten by the nested scope.

5
Exploring the Variety of Random
Documents with Different Content
The time came when Dr. Mateer had a shop equipped to do a
great variety of work; and though not on a large scale, yet big
enough to meet his needs. Already in 1886 in a letter to his brother
William he said: “In order to repair apparatus, and in order to make
many simpler articles, I have fitted up quite a complete workshop,
entirely at my own expense. I have invested in the shop, in tools and
materials quite one thousand dollars. I keep a workman at my own
cost, whom I have trained so that he can do most ordinary kinds of
work. There are a great many small articles we can make here more
cheaply than we can buy them. There are, however, many articles
we cannot make, especially those that involve glass or the use of
special machinery, or special skill.” That shop continued to grow, and
the variety of its output increased. Writing of this, Mrs. Ada Mateer
says:

So soon as possible in addition to the room used for


carpenter work, a side house was devoted to the purposes of
a shop, which grew in completeness as time went on. An
upper story was used for storing finished apparatus, for a
painting, varnishing, and drying room. The lower story was
the shop proper, with well, smithy, a long workroom, private
room for chemicals and so forth. Every conceivable amount of
space in the shop—above, around, and below—was occupied
with materials, on boards hung from above, in cases made of
old boxes lining the walls, and on the floor. The shop
contained not only materials for things that are to be, but
became also a tomb of things that were, but are not, as well
as a hospital for things disabled. What old histories were
unearthed when, after forty years, this shop had to be moved
to Wei Hsien!

Up there it was perpetuated, the main difference consisting in


larger and better quarters, with some improved conveniences. His
wife continues:
For every machine bought, the market was canvassed by
correspondence, and the best selected. Especially was this
true with reference to any tools or machinery used in the
construction of apparatus,—as machines for turning,
blacksmithing, plumbing, screw-cutting, burnishing,
electroplating, casting, and so forth. His shop was thoroughly
fitted with all appliances for the making of apparatus, or
electric or steam outfitting, so that he was ready to do
anything, from setting up a windmill or water system, or
installing an engine and dynamo, to brazing broken spectacle
frames or repairing a bicycle.

So far as it was practicable he turned over the actual mechanical


labor to Chinese workmen,—a skilled foreman and apprentices
under the foreman’s direction.
Why, though a missionary, did he employ so considerable a part of
his time in this way? Especially at the outset of his missionary career
stern necessity to meet his own needs and those of his associates
drove him to this line of work. Had he been set down in China at
some such place as Shanghai, where foreign articles could be
purchased, very likely his mechanical gifts would have remained
largely dormant. But at Tengchow he helped to make a stove out of
odds and ends, because one was indispensable in order to keep
warm. For the same sort of reason he extracted teeth and made
false sets, cobbled shoes, and acted as master workman of all the
building trades in the erection of the “new home.” Sometimes he was
thus compelled to do things which seemed strange even to him.
When, in 1865, little Katie Mills died, he had to act the part of
undertaker. He said:

It fell to me to make the coffin, which I did as well as I could


from memory. I could not tell the carpenter, and I had to do
the work myself. He did the rough work, and I did the cutting
and fitting. I had to go entirely by my eye, and I found it no
easy matter to get it in every respect in proportion. We
covered it with black velvet outside, and inside with white
linen. It looked very well when finished, and pleased Mr. and
Mrs. Mills very much. It is a work I never thought of doing.

At one point on the way through Siberia when homeward bound


on his last furlough the train was halted by some defect in the
working of the mechanism of the locomotive. Dr. Mateer, on account
of the delay, got out of his compartment and went to see what was
the matter. He saw that the locomotive was a huge Baldwin, with
whose construction he had familiarized himself when in the United
States on a previous furlough, and he quickly discovered the cause
of the trouble. He could speak no Russian, and the men in charge of
the engine could speak no English, but he managed to show them
the cause of the defective working of the mechanism, and how to
remedy it; and soon the train was again speeding on its way.
The time never came during his long residence in China when a
necessity did not occasionally force itself on him to utilize his
mechanical gifts, and not infrequently on the common utensils of life.
In Wei Hsien he often spent hours directing in such repairs as were
needed for furnaces and the like.
Few of his later and larger achievements in this field could be fairly
regarded as works of necessity, strictly speaking; they rather were
meant to be aids in the great enterprise of evangelizing the Chinese
Empire. He was thoroughly convinced that one of the most powerful
agencies that could be employed for this purpose was the school
and the college. He was equally sure that of all the studies that could
be introduced into the curricula of these institutions, none could be
so effective in opening the way for the gospel as that of the natural
sciences, and especially physics, inclusive of modern mechanical
appliances of its principles. He believed that if bright young men
were educated in that kind of knowledge, and sent out under
Christian influences among their own people, if they were also
converted to Christianity, the outcome must be the dissipation of the
existing blind adherence to the superstitions and ideas of centuries
long remote in the past; and that with this must come the opening
wide of the door for the entrance of Christianity. That was his
forecast; and the present situation in China goes far toward
vindicating the wisdom of it. But to teach effectively the natural
sciences he must have apparatus. The only way he could secure this
was by buying what he could, and by utilizing his own ability to set
this up, and to add as much as possible for the outfit yet needed.
Such was the prime object not only of what in a more limited sense
constituted the apparatus of the school and college, but also of such
larger appliances as the plant for heating and lighting the premises.
These were far more than conveniences that helped to better work;
they were themselves constant exhibitions to the students and to the
people at large of the principles of natural science, and of their value
in the affairs of actual life.
Dr. Mateer utilized his outfit of apparatus and machinery as a
means of reaching others besides the students in his own institution,
with the influence of modern science, thus opening a way into their
minds for the gospel. As to one of his methods of accomplishing this
object Ada gives a graphic account:

At the time when the official examinations were held in


Tengchow, a large number of scholars came to town, hoping
to secure a degree, which should be the first step toward
official preferment. So many of these, having heard the fame
of the foreign machine, came to see and to hear, that Dr.
Mateer used to give up his time to them during the days they
were at leisure. Finally the opportunity to do good in this way
proved so great that a place was provided for the purpose,
which was also much used at the Chinese New Year, when all
the town and countryside give themselves up to recreation.
After the “Mandarin Lessons” began to bring in money, he
devoted the profits to the building of a large museum, with an
entrance on the street. One half was a big audience room, so
arranged that it could be darkened down for stereopticon or
cinematograph exhibitions. But it usually served as an
audience room, where the crowds could sit and listen to
preaching, while the detachment that preceded them was
shown through the inner room by expert assistants. What a
chamber of wonders that inner room proved to them! Here
was a man, using a single hand to turn a small crank, grinding
corn as fast as a woman or a donkey could do it on the
millstones with much more labor. Here in cases were birds
stuffed, and on the walls pictures of strange animals. Here
was a man turning a large crank that in some mysterious way
made a little iron car overhead first send out sparks, and then
run all around the room on a circular railroad. They wondered
if it would not have been easier for the man to drag the car
around on the ground! There was an oil engine at the end of
the room, that was a wonder, no mistake; and a “shocking”
machine that shocked them indeed; and untold other
wonders. When the tour of the room was finished, the crowd
was let out by another door, their almond eyes quite round,
while a signal given by a steam siren showed it was time for
the next group to go in, and “open-open-eyes,” as they call
sight-seeing.

Occasionally a mandarin of high order came to witness the


marvels. The report of the Shantung Mission for 1909 says that
through the agency of the chapel and museum twelve thousand
people were brought into touch with the gospel during the year; so
the work still continues.
Another good account to which Dr. Mateer turned this peculiar gift
was that of starting industries for native Christians and promoting
self-help among the needy. Now it was a loom for weaving coarse
Chinese linsey or bagging, or a spinning or a knitting machine, that
he ordered; again, he inquired for a roller press to be used for drying
and pressing cotton cloth after dyeing; and more than once he sent
for a lathe for a Chinese blacksmith. In 1896 he interested himself in
procuring an outfit for a flouring mill. He said: “The enterprise of
starting the mill was conceived by Chinese Christians, and they are
going to form a company to raise the money. I do not think that there
is a roller mill in China,—certainly not in north China.... We
personally will not make a cent out of it; but we are interested to get
the Chinese Christians started in an enterprise by which they can
make a living, and introduce improvements into their country.”
His apprentices went out in many instances master blacksmiths,
machinists, and electricians, and had no difficulty in finding places. A
Chinese general temporarily at Tengchow employed one of these
men as a blacksmith, and his order was so evidently filled according
to western methods that he paid a visit to the wonderful shop of this
wonderful master. The very last man for whom he obtained a place
was his most skilled electrician and his latest foreman. This man
started a shop up at the capital of the province, and for its outfit Dr.
Mateer carried on an extensive correspondence and procured large
invoices of goods. Because of the provincial university established
there under the new educational régime there was imperative need
of such an establishment, and the outlook for success was excellent.
Unfortunately for the proprietor, however, the Chinese officials were
equally alive to the opportunity and were jealous of a rival. So they
managed to compel him to sell out, though they broke the fall a little
for him by retaining him as foreman. It is said that the thought of this
workman’s troubles lay heavy on the heart of Dr. Mateer in his last
illness. It was usually for the poor that he interested himself after this
practical fashion; yet he did not refuse to lend aid to others in
promoting enterprises that would be of general advantage. For a
wealthy Chinaman who owned a coal mine that had been flooded
with water he went to a great deal of trouble in order to put him in the
way of securing a suitable pump. But whether it was for rich or poor
that the opportunity came to render such services, he put aside all
thought of his own ease or name or profit, and did the best in his
power.
He had special satisfaction in the manufacture of electrical
machines, though it was no easy matter to cut and bore the large
glass wheels without breaking them, and to adjust all parts so that
the greatest efficiency was attained. Ada says:

When a machine was perfected, giving an unusually long


spark, he always liked to take me over at night to the shop to
see it perform. I well remember the last time,—at Wei Hsien.
At one end of the shop was the windmill. Here he stopped to
show me a way of equalizing the stroke of the windmill pump
piston, by hanging on an old kettle of scrap iron. Then he took
me into an inner room, where on one end of a long table
stood the newly finished machine,—a beauty, no mistake.
Having forgotten some necessary key, he took the lantern and
went to get it, leaving me in the dark. I noticed sounds, the
dripping of water in the well; but what was the ticking I heard?
On the return of the lantern I saw the cause,—a number of
clock dials all hung on the wall, and all to be run by one clock
by means of electricity. These were for the college recitation
rooms when they should be finished. Then Calvin made the
new machine do its work. Adjusting carefully the mechanism,
and then measuring the spark, he exclaimed with boyish glee,
“There, isn’t that a beauty!”

Dr. W. A. P. Martin, of Peking, related in the “Chinese Recorder” of


December, 1908, this incident as to Dr. Mateer: “It was once my
privilege to spend part of a vacation in his hospitable home at
Tengchow. I found him at work constructing scientific apparatus with
his own hands and wrestling with a mathematical problem which he
had met in an American magazine. When I solved the problem, he
evinced a lively satisfaction, as if it were the one thing required to
cement our friendship.” The problem was to find the diameter of an
auger, which, passing through the center of a sphere, will bore away
just one half of its bulk. It is easy to see that to a man of that sort his
work and the scientific and practical problems constantly arising in
connection with the making of apparatus and the adjustment of
machinery must have been in themselves a rich source of pleasure,
though he never allowed himself to be so fascinated by his shop as
to break in on what he conceived to be his higher work. Speaking of
his last years, Ada says: “He would go out wearied with the baffling
search for a way of expressing clearly in Chinese a thought none too
clear in the original Greek, his forehead grooved with the harrows of
thought. He would come back from the shop an hour later, with well-
begrimed hands, a new spot on his long Chinese gown, a fresher
pink in his cheeks, a brighter sparkle in his eyes, and his lips parted
with a smile. Then, having washed, he would immediately set himself
again to the work of revision.”
He loved also to share this joy, so far as it could be done, with
others. At the Synod of China with his apparatus he gave several
exhibitions that were greatly appreciated. At Wei Hsien he rendered
similar services in the high schools, and at Chefoo in the school for
the children of missionaries. The Centennial Fourth of July, being
quite an exceptional occasion, he celebrated not with ordinary
gunpowder, but by setting off a considerable quantity of detonating
chemicals. In the early days at Tengchow a home-made electric fly
whisk whirled above the dining table, and a little pneumatic fountain
playing in a bell glass rendered the room and the meals additionally
pleasant to the family and to the guests. Ada writes:

But the thing that most of us will remember longest is an


illustrated lecture on electricity delivered to the college in Wei
Hsien, and afterward to the foreigners there. As we sat in a
darkened room in the college watching the long sparks of fire,
the twisting circles of many-colored light, half illuminating a
tall, white-bearded figure in a long black gown, he seemed to
us like some old magician, learned in the black arts, now
become bright arts, invoking to his aid his attendant spirits.
Nor was the enchantment diminished when afterward, more
wonderful than a palmister, he showed us by the x-rays the
bones of our hands. A few weeks later one of the ladies of the
compound gave an evening entertainment in which each one
in the station was hit off in some bright way, and we were to
guess the name. One number of the programme was this: A
black-robed figure with cotton beard appeared, leading a
youth whom he seated in a chair. Then the venerable
personage proceeds to examine the head of the stripling with
a stereoscope covered with black cloth, supposed to be a
fluoroscope, while an alarm clock in a tin pail near by supplies
the crackling of electricity. He gives a careful examination,
shakes his head, and pronounces the verdict in one word,
“Empty.” In explanation of the tableau it only needs to be said
that between the exhibition and the entertainment Dr. Mateer
had given the young men of the station their examination in
the language.
XIII
THE MANDARIN VERSION

“I am mortgaged to the Bible revision work.... It cost me a great effort to


engage in it, but it will probably be the most important work of my
life.”—letter to secretary brown, June 13, 1896.

To tell this part of the story of Dr. Mateer’s life satisfactorily, I must
begin with the first general missionary conference, held at Shanghai
in May, 1877. For two years previous he had served on a committee
to prepare the way for the meeting, and in this capacity he had
rendered much valuable assistance. At that conference he read a
paper in which he elaborately discussed the subject of “The Relation
of Protestant Missions to Education.” The meeting was regarded as
successful, and a second was called, to assemble at Shanghai, in
May, 1890. It was at this conference that the movement for a revision
of the Bible in Chinese took actual measures toward realization.
For the sake of any readers not well informed as to the Chinese
language, a few preliminary statements concerning it may be
desirable here. In a very broad and general sense it may be said that
as to elements, one tongue prevails throughout China proper; but
that there is also much important variation in this general tongue.
First of all, it needs lo be noted that the language takes on two
principal forms,—the classic, or Wen-li, and the spoken, or
Mandarin. The classic has come down through the centuries from
the times of Confucius and Mencius, and remains comparatively the
same as it is found in the writings of those sages. This is accepted
as the model for all writing; and for that reason Chinese students
have been required to spend the greater part of their time in
memorizing those ancient books, so that they might not only absorb
their teaching, but also especially that they might be able to
reproduce their style. The classic Chinese is stilted and so
condensed that in comparison with it a telegram would seem diffuse;
and though many of the characters are the same as those used in
writing the spoken language, yet the meaning and often the sound of
characters is so different that an illiterate person would not
understand it on hearing it read. The spoken language, on the other
hand, may be compared with English as to its use. Good English is
very much the same throughout the countries where it is the
vernacular, and though it takes on local dialects, it remains
everywhere intelligible. So, broadly speaking, is it also as to the
spoken Chinese in a large part of the empire. From the Yangtse up
into Manchuria, though the pronunciations differ very much, the
colloquial if put into writing is understood. In other words, with
differences of dialect and pronunciation it is the speech of perhaps
three hundred millions of people. The regions excepted lie along the
coast from Shanghai down, and inland south of the Yangtse, where
the distinct tongues are numerous and are largely unintelligible
except in their own localities.
It has been the rule in China that a mandarin must not be a native
of the province where he holds office; and, of course, it is essential
that he should be acquainted with the speech which constitutes the
lingua franca. Perhaps for this reason it is called Mandarin. But down
to the time when missionary publications rendered it common in
print, it was not employed in that mode. All books, business or
government documents, the one newspaper of the country, which
was the court gazette, and all letters were in the higher or, as it is
called, the Wen-li form, the only exception being some novels, and
even these were streaked with Wen-li. This, however, ran through
gradations,—from the highest, which is so condensed and so bristles
with erudite allusions that only a trained scholar can understand it,
down to a modification which is so easy that with a slight alteration of
particles it is almost the same as the Mandarin.
During the long period of the nineteenth century preceding the
meeting of the second general missionary conference, a number of
translations of the Scriptures, some of them of the whole, and some
of parts, had been made, and had come more or less into use. The
men who did this pioneer work deserve to be held in perpetual
esteem, especially in view of the difficulties under which they
labored. Among the missionaries who sat in that conference there
was no disposition to withhold this honor, or to disparage the value of
these early translations; but there was so widely prevalent among
them and their associates at that time on the field a conviction that
no existing version was satisfactory, that they recognized it as a duty
to take up the subject, and to initiate steps looking to the production
of a better. An informal consultation as to this was held by a few
men, a couple of days before the conference assembled; but
inasmuch as Dr. Mateer had not been invited, he did not attend.
Another consultation was held the following day, and because of his
great interest in the subject of a Bible revision, he attended without
an invitation. The views expressed clearly indicated that there was a
general agreement that a revision was desirable, but it also was
made very plain that beyond this there was a wide divergence of
opinion. We will allow one of his letters to a representative of the
American Bible Society, under date of May 26, 1890, to tell the next
step in this great undertaking:

As I walked home from the meeting, and revolved in my


mind the difficulty of the situation, the idea of an executive
committee, to whom the whole work should be intrusted,
came across my mind. When I reached my room I sat down,
and in a few minutes and without consultation with anyone,
wrote out the plan, which without essential modification was
subsequently adopted. It seemed to strike all parties very
favorably. On the second day of the conference two large,
representative committees were appointed by the conference,
one on Mandarin and one on Wen-li. I was a member of both
these committees. Each committee had a number of
meetings, in which the subject was freely and fully discussed
in all its bearings. It was evident that there was a general
desire for a version in simple Wen-li, and, the difficulties being
less in regard to the work already done, a conclusion was first
reached in regard to this version. In Mandarin the difficulties
were greater.
An agreement, however, was reached. The version in the higher
classic style then gave the most trouble, but a satisfactory basis for
this also was agreed upon; and the reports as to all three versions
were adopted unanimously by the conference. In the same letter he
says: “I worked hard for these results, and felt no small satisfaction
in seeing such perfect unanimity in the adoption of the plan
proposed. I have never done anything in which I felt more the
guiding hand of God than in drawing up and carrying through this
plan.”
The selection of translators for each of the projected new versions
was handed over respectively to executive committees; and Dr.
Mateer was appointed on that having charge of the Mandarin, and
made chairman of it. He heard that he was talked of as one of the
revisers for that version, but as yet he had not decided what was his
duty, if chosen. It will again be best here to take up from one of his
letters the thread of the narrative. Under date of December 13, 1890,
he writes to Dr. Nevius:

I can truly say that before I went to the conference I never


even dreamed of what has come to pass. It never occurred to
me, before the conference, that I should take any prominent
part in the matter of Bible translation. I felt that education was
the only field in which I should come to the front. I was never
in my life so providentially led as I was in this matter. I was
selected chairman of the Mandarin Executive Committee and
have been pushing the getting of translators. The first few
months were spent in corresponding and comparing notes as
to men. We took a ballot recently, which resulted in the
election of five, ... I being the only one who received a
unanimous vote. We are now voting for the others, to make
up the seven.... My book of “Mandarin Lessons” has no doubt
brought me forward, and its preparation has in a measure
fitted me for the work. My personal preferences are against
the work of translation, and I would fain decline it, but I don’t
see how I can in view of the circumstances. I feel my
incompetency, especially in Greek and Hebrew, and you may
be sure I am very loath to give up the educational and literary
work on my hands. Much of it is half finished. But if the
Mandarin Bible is to be made, some one must do it;
moreover, the men who do it must have the confidence of the
missionary body; otherwise it will be a failure. As it is,
circumstances have led me to the position, and the strong
opinion of the men on the committee, and of others, leads me
to feel that I cannot lightly refuse.

In November, 1891, the revisers met at Shanghai. Dr. Mateer, in a


letter written in the following January, said:

The scheme for the revision of the Chinese Bible set on


foot by the conference is now fairly organized, and approved
by the three great Bible societies. The work of pushing the
organization has fallen largely on me, and I feel no small
sense of relief now that it is successfully accomplished.
Contrary to my own desire, I am compelled to lake a share as
one of the revisers in Mandarin; not that I do not relish the
work, but because it will of necessity interfere with many of
my cherished plans. We had a meeting of all the revisers of
the three versions, and it was a fairly harmonious and an
altogether successful meeting. A great work is before us
which I trust we may, in the good providence of God, be
enabled to accomplish.

The interval of about a year and a half between the general


conference and the organization just mentioned was required
because of the difficulty of selecting and securing the translators.
These for the Mandarin version, as that body was originally
constituted, consisted of Henry Blodgett, George Owen, Chauncey
Goodrich, J. R. Hykes, Thomas Bramfitt, J. L. Nevius and C. W.
Mateer. During the years in which this work was continued there
were in the membership so many changes caused by death, removal
and other causes, that Dr. Goodrich and Dr. Mateer alone continued
from the beginning until the translation of the New Testament, the
part of the Bible first revised, was tentatively completed. Mr. Baller of
the China Inland Mission stands next in length of service, having
joined the committee in 1900. Dr. Mateer in the work of revision had
the assistance of two Chinese Christians whose services were so
large and valuable that they deserve more than a passing mention
here. In a recent letter Dr. Goodrich pays them the following just
tribute:

Dr. Mateer, in the work of rendering the Scriptures into a


universal Mandarin colloquial, had two exceptionally fine
teachers. The first was Mr. Tsou Li Wen, an ordained pastor,
who left his parish to engage in this work. Mr. Tsou was
trained by Dr. Mateer in his college, receiving his theological
training under Drs. Nevius, Mateer and others. He was a man
of beautiful spirit, discriminating mind, and a fine sense of
language. He was also a man of indomitable perseverance.
After a strenuous day’s work of eight hours or more, he would
often toil by himself far into the night, seeking for some
phrase or phrases which expressed more exactly or more
beautifully the meaning of the original. And before the final
review, both he and my own lamented teacher (Chang Hsi
Hsin) would bestow the greatest pains, in the hours when
they should have been sleeping, in a careful inspection of the
work. Thus did Mr. Tsou toil, while separated from his family
for long periods of time; his work on Bible revision being as
truly a labor of love as that of any member of the committee.
But alas! Mr. Tsou’s life burned out all too soon in his
exhausting labors. But how I should like to see his crown, and
his shining face!
Happily for the work, Dr. Mateer had another scholar,
trained also in his school, Mr. Wang Yuan Teh, a young man
of keen, incisive, logical mind, who had read all the best
books in the Mandarin colloquial. Mr. Wang was quick to see
any fault in the structure of a sentence, and insistent on its
being put right. He also worked most faithfully in this
translation, refusing offers which came to him of a salary
several times the amount he received. I think he was held,
partly by Dr. Mateer’s personality, which drew him strongly,
and partly by his own love for the work itself. When the chariot
of fire came for Dr. Mateer, he left us, much to our regret and
loss.
The work of these two men has entered largely into the
present translation of the New Testament, and the influence of
their work, as of Dr. Mateer’s, abides, and will continue to be
felt, till the great work of rendering the Bible into a universal
Mandarin is finished.

Dr. Mateer himself, in the preface to his “Mandarin Lessons,”


makes acknowledgment of the valuable services rendered in the
preparation of that work by Tsou Li Wen, and also by his own wife.
The Mandarin Committee, at the meeting in 1891, after
organization, proceeded to divide up the books of the New
Testament among themselves for work, and adopted a plan of
procedure. Each man was first carefully to revise or translate his own
portion; and then to send it around to the others, who were to go
over it, and write their suggestions of emendations, each in a column
parallel to the proposed text. Next, the original translator was to take
these emendations, and with their help was to prepare a text in
Mandarin for submission to the entire committee. Broadly speaking,
this was the method pursued to the end, though with some
modifications compelled or suggested by experience. It was hoped
that comparatively rapid progress would be made; but in reality the
committee did not come together again until September, 1898; and
even then, only the Acts of the Apostles was ready for general
revision. For this delay there were various causes, such as the death
of Dr. Nevius and the resignation of others, and the absence of Dr.
Mateer on furlough home; but the chief cause was that every
member was burdened with so much other work that only a fraction
of his time could be given to this duty. Dr. Mateer, for example, found
himself loaded down with other literary and missionary labors. At the
meeting held at Tengchow, in 1898, he was elected chairman of the
committee. This was an honor, but it also carried with it peculiar
duties which materially added to his burden. The committee could
muster only five members for that sitting, but they proceeded with
their work, and at the end of two months and a half they finished the
book of Acts; and then they separated.

MANDARIN REVISION COMMITTEE AT WORK

DR. S. LEWIS DR. DR. MATEER M. BALLER


(American Methodist GOODRICH (Presbyterian) (China Inland
Episcopal) (Congregational) Mission)

That meeting by actual experience brought out distinctly not only


the difficulties of necessity arising from the translation of particular
books of the Bible, and indeed of every verse; but also others of a
more general character, some of which had previously been more or
less clearly seen. Should the new version take as its basis one or
more of the translations already in existence; or should it go back
straight to the original Greek, and use the existing translations
merely as helps? In any case, constant reference to the original was
a necessity. For this, which of the published texts should be
accepted as the standard? The meeting also disclosed a wide
divergence of opinion as to the style of Mandarin that ought to be
employed. On that subject in 1900, Dr. Mateer expressed himself
fully and strongly, in an article published in the “Chinese Recorder.”
He said:

The Mandarin Bible, in order to fulfill its purpose, should be


such as can be readily understood by all when heard as read
aloud by another. The fundamental distinction between Wen-li
and Mandarin is that the former is addressed to the eye, the
latter to the ear. In all Protestant churches the reading of the
Scriptures has, from the first, constituted an important part of
public worship. In order that this reading may serve the
purpose intended, the Scripture must be so translated as to
be intelligible to the common people. Only thus will they hear
it, as they did its Author, “gladly.” It is not enough that those
who know “characters” should be able to read it intelligently,
but rather that those who do not know “characters,” and who
in fact constitute by far the greater part of the Chinese people,
should be able to understand it when it is read to them. Here
then is the standard to be aimed at,—a version that
represents the Chinese language as it is spoken, and
addresses itself to the ear rather than to the eye.

He summarized the chief characteristics of the proper style thus:


that words should be employed which the people who commonly use
Mandarin can understand; that sentences should conform to the
model of the spoken language; and, concerning both of these
requisites, that such care should be taken as to brevity, the order of
words and clauses, the connective particles, and the evident
movement of thought as expressed, that the Chinese would
recognize in it a people’s book; and yet one that is free from
undignified colloquialisms and localisms. All this he held up as an
ideal, not likely to be fully realized by any set of translators, but if
distinctly aimed at, more sure to be nearly approached. Toward the
close of the work on the Mandarin version still another question of a
general nature arose. Throughout most of their labors the committee
had before them the revised easy Wen-li translation, and for a part of
the time they also had the revised classic Wen-li Bible. Ought the
three revised Chinese versions to be harmonized, so as to eliminate
all variations? That, of course, would be ideal. On this question the
report of the Mandarin Committee, which was as to substance
prepared by the chairman, took the negative. It said:

The differences are not great, and where they exist, the
versions will serve Chinese students as a sort of commentary.
There are a multitude of questions in Biblical interpretation
which no translation can settle once for all. Moreover, ninety-
nine out of a hundred of those who use the Mandarin will
never look at any other translation. Two versions in perfect
accord seem like a fine product, but it is difficult of realization.
An attempt at reconciling the present versions would develop
many difficulties. A Mandarin sentence especially is not easy
to tamper with. The change of a single word would often
dislocate a long sentence, and necessitate retranslation and
adjustment to the context.

The Mandarin committee of translators continued their tentative


revision of the New Testament until late in 1906, a period of fifteen
years, counting from the date of their first meeting for organization
and assignment of specific duties. They held eight different sessions,
being almost one each year after they were ready with actual work;
and none of the sessions were shorter than two and a half months,
and one of them stretched out to six months. They assembled at
Tengchow, near Peking, at Shanghai, and most frequently at Chefoo.
In the final report is the record: “The chairman can say for himself
that he has given the equivalent of about seven years all-day labor to
this work. He was present at every meeting, and first and last missed
but one day’s session.” Each of the meetings took on distinctive
incidental associations. The third was held at Shanghai, and from
December, 1900, ran over some months into 1901. At that time, on
account of the Boxer uprising, missionaries were temporarily there
as refugees from all the provinces directly concerned in the version.
The sittings were in a small upper room in the Union Church, which
came to be called “the Jerusalem Chamber,” and visitors were many.
They saw two rows of men, one on each side of a long table, yellow
faces being sandwiched alternately with white, as each translator
had, as usual in this work, his Chinese assistant at his side. Often
the discussions were carried on in Mandarin, so that these assistants
might be able to understand and pass their opinion. Incidentally it
may be noted that besides his work on the revision, Dr. Mateer often
met with the refugee missionaries during this period and greatly
gratified them by participating in the discussion of practical problems.
After the Mateers returned from their furlough, the sessions were
all held at Chefoo, first in one of the rooms of the China Inland
Mission Sanitarium, and later in a large upper room in the Missionary
Home, overlooking the bay. Usually at the commencement of their
meetings they sat together for three hours in the morning, and
reserved the rest of the day for such private study as they wished to
make; but as the time wore on they would increase the sittings to as
many hours also in the afternoon, and crowd the private review into
such odd moments as were left. To anyone, these protracted labors
on such a work must have become exceedingly tedious and almost
irksome; but to no one was it more so than to Dr. Mateer. He knew
Mandarin almost as if it had been his native tongue; but the
Mandarin which he knew had often to be modified and expressions
adjusted, so that a Scripture written in it would suit other regions of
China as well as those with which he was familiar. In writing his
“Mandarin Lessons” and in preparing his educational books he had
only to ascertain to the best of his ability how to express his ideas in
Chinese, and that was the end of the search; but here he had to do
his best, and then submit his product to the opinion of others, and
often with the result of changes which did not commend themselves
to his preference. Yet, on his return home from the sittings he would
say: “I ought not to complain. I get my way oftener than any other
man does. Only I cannot help thinking of the work I have laid aside
unfinished in order to do this.” After each meeting the year’s work
was printed, marked “Tentative Edition,” and with a slip inviting
criticism was sent to the missionaries in north China and Manchuria.
These criticisms were all to be canvassed before the edition could be
printed that was to be presented to the Centenary Conference, to
which they were to report.
The final meeting for the tentative revision of the New Testament
lasted for more than five months, and the work was pushed with
even more than the usual vigor. The Centenary Missionary
Conference for China was only a year ahead when they began. After
the conference the revision was to run the gauntlet of criticisms, and
these were to be canvassed; and thus at last the revision was to take
its permanent form. Mrs. Mateer gives the following graphic account
of one of the closing incidents of that session.

Passage had already been engaged for the Goodrich family


on a steamer sailing north. The baggage was all carried
down, the family all waited on the upper veranda, with hats
on, and the Doctor’s hat was ready for him to seize as soon
as he should get out of the meeting. The “rickshaw” men were
waiting, ready to run with their loads. But still no sound of
approaching feet! Finally, as it got dangerously near the hour
of sailing, Mrs. Goodrich said, “I must go and hurry them up.”
So she marched boldly down the hall, listened a minute at the
door, and came back with her fingers on her lips. “Those dear
men are praying,” she whispered; and tears filled our eyes as
our hearts silently joined in the prayer. Of course, every
morning session was opened with prayer; but this was the
consummation of all these years of toil, the offering of the
finished work at the altar.

Although the committee completed their revision at that session,


so far as this was possible until the conference should meet and
approve or disapprove it, there was very considerable work of a
tedious nature left to Dr. Mateer to perform. The finishing touches yet
to be put upon portions of the version were not a few; but the thing
that required of him the most protracted and delicate attention was
the punctuation. For this he introduced a new system which seemed
to him to be best for the Chinese language, and which can be
estimated fairly only by a scholar in that tongue. To him also as
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like