Whenever the word JavaScript is mentioned to a room full of .NET developers, there are visible shudders and uncomfortable fidgeting at the prospect of writing anything in such a sloppy language. I actually love JavaScript, partly because it was the first curlybraced language that I used, but also because I have learned to use it an appropriate way. However, I can understand the reasons for its lack of popularity amongst the .NET community. If you spend most of your time writing code in C, VB.NET, or F, the prospect of using a language that lacks sensible autocompletion, type checking, and objectorientation is not a pleasant one—and this is where TypeScript fits perfectly into the tool belt of a .NET programmer
1 2 By Steve Fenton Foreword by Daniel Jebaraj 3 Copyright © 2013 by Syncfusion Inc. 2501 Aerial Center Parkway Suite 200 Morrisville, NC 27560 USA All rights reserved. mportant licensing information. Please read. This book is available for free download from www.syncfusion.com on completion of a registration form. If you obtained this book from any other source, please register and download a free copy from www.syncfusion.com. This book is licensed for reading only if obtained from www.syncfusion.com. This book is licensed strictly for personal, educational use. Redistribution in any form is prohibited. The authors and copyright holders provide absolutely no warranty for any information provided. The authors and copyright holders shall not be liable for any claim, damages, or any other liability arising from, out of, or in connection with the information in this book. Please do not use this book if the listed terms are unacceptable. Use shall constitute acceptance of the terms listed. SYNCFUSION, SUCCINCTLY, DELIVER INNOVATION WITH EASE, ESSENTIAL, and .NET ESSENTIALS are the registered trademarks of Syncfusion, Inc. dited by This publication was edited by Praveen Ramesh, director of development, Syncfusion, Inc. I E 4 Table of Contents The Story behind the Succinctly Series of Books 8 About the Author 10 Introduction 11 Is TypeScript the Answer? 11 Who is This Book For? 11 What is Missing? 12 Code Samples 12 Notes 12 Chapter 1 Concepts in TypeScript 13 Code organization 13 TypeScript Glossary 14 Program 14 Module 14 Interface 14 Class 14 Function 14 Variable 15 Enumeration 15 Scope 15 Compilation 15 ECMAScript 3 15 ECMAScript 5 16 ECMAScript 6 16 TypeScript Life Cycle 16 5 Chapter 2 Visual Studio 18 Visual Studio Extension 18 Pre-Build Event 19 Trying it Out 20 Chapter 3 Type Safety 21 Static, Dynamic, and Optional Types 21 Inferred Types 21 Built-in Types 25 Custom Types 27 Advanced Type Declarations 27 Type Inference Mechanism 29 Variables and Parameters 29 Functions 30 Contextual Typing 30 Widened Types 31 When to Use Types 31 Chapter 4 Creating New Modules 32 Modules 32 Declaring a Module 32 Adding a Class to a Module 33 Interfaces, Classes, and Functions 35 Private Functions 35 Static Functions 37 Default Parameters 38 Optional Parameters 39 Rest Parameters 40 Function Overloads 40 6 Constructors 42 Interfaces 43 Multiple Interfaces 44 Duck Typing 44 Inheritance and Polymorphism 45 Multiple Inheritance 46 Using instanceof 47 Chapter Summary 48 Chapter 5 Loading Modules 49 Bundling 49 Module Declaration Style 49 Module Referencing Style 50 Script Loading Style 50 Summary 51 CommonJS Modules 51 Module Declaration Style 52 Module Referencing Style 52 Script Loading Style 52 Summary 53 AMD Modules 53 Module Declaration Style 53 Module Referencing Style 53 Script Loading Style 54 Chapter Summary 54 Chapter 6 Working with Existing JavaScript 55 Creating Ambient Declarations 55 Porting JavaScript to TypeScript 57 7 Transferring Design Patterns 59 Chapter 7 Unit Testing with TypeScript 60 Testing with tsUnit 60 Setting it Up 60 Code under Test 60 Writing a tsUnit Test 61 Running the Test 63 Test Composition 65 Test Context Assertions 66 Test Doubles 68 Lightweight Fakes 70 Running Tests in Visual Studio 71 Unit Test Project 71 Referencing the Script Files 74 Adjusting the TypeScript Test 75 Creating the Unit Test 76 Testing with a JavaScript Framework 78 Summary 79 Appendix A: Alternative Development Tools 80 Appendix B: TypeScript Command Line 81 Appendix C: External Resources 82 8 The Story behind the Succinctly Series of Books Daniel Jebaraj, Vice President Syncfusion, Inc. taying on the cutting edge As many of you may know, Syncfusion is a provider of software components for the Microsoft platform. This puts us in the exciting but challenging position of always being on the cutting edge. Whenever platforms or tools are shipping out of Microsoft, which seems to be about every other week these days, we have to educate ourselves, quickly. Information is plentiful but harder to digest In reality, this translates into a lot of book orders, blog searches, and Twitter scans. While more information is becoming available on the Internet and more and more books are being published, even on topics that are relatively new, one aspect that continues to inhibit us is the inability to find concise technology overview books. We are usually faced with two options: read several 500+ page books or scour the web for relevant blog posts and other articles. Just as everyone else who has a job to do and customers to serve, we find this quite frustrating. The Succinctly series This frustration translated into a deep desire to produce a series of concise technical books that would be targeted at developers working on the Microsoft platform. We firmly believe, given the background knowledge such developers have, that most topics can be translated into books that are between 50 and 100 pages. This is exactly what we resolved to accomplish with the Succinctly series. Isn’t everything wonderful born out of a deep desire to change things for the better? The best authors, the best content Each author was carefully chosen from a pool of talented experts who shared our vision. The book you now hold in your hands, and the others available in this series, are a result of the authors’ tireless work. You will find original content that is guaranteed to get you up and running in about the time it takes to drink a few cups of coffee. S 9 Free forever Syncfusion will be working to produce books on several topics. The books will always be free. Any updates we publish will also be free. Free? What is the catch? There is no catch here. Syncfusion has a vested interest in this effort. As a component vendor, our unique claim has always been that we offer deeper and broader frameworks than anyone else on the market. Developer education greatly helps us market and sell against competing vendors who promise to “enable AJAX support with one click,” or “turn the moon to cheese!” Let us know what you think If you have any topics of interest, thoughts, or feedback, please feel free to send them to us at succinctly-series@syncfusion.com. We sincerely hope you enjoy reading this book and that it helps you better understand the topic of study. Thank you for reading. Please follow us on Twitter and “Like” us on Facebook to help us spread the word about the Succinctly series! 10 About the Author Steve Fenton is an Agile .NET developer with a keen interest in the web stack. He has been creating business applications since 1997 and writing web applications since 2001. He is currently keeping an eye on emerging standards and techniques for web development and was an early adopter of the HTML 5 standards, releasing his first HTML 5 website in 2009. Steve is well versed in JavaScript and has dabbled with alternatives such as Flash, Silverlight, CoffeeScript, and Dart, but always preferred writing raw JavaScript—until he tried TypeScript in 2012. In his spare time, Steve attends conferences, runs brown-bag learning lunches, reads books in his local coffee shop, and attends ice hockey matches. TypeScript is a trademark of Microsoft Corporation. [...]... able to target the ECMAScript 6 standard from TypeScript, which will mean the compiled JavaScript will more closely match your TypeScript code There is currently no release date planned for ECMAScript 6, and it doesn’t support all of the concepts in the TypeScript language TypeScript Life Cycle The TypeScript life cycle consists of three distinct stages When you are writing TypeScript code, you are participating... right up until JavaScript checks the global scope Compilation TypeScript is converted into JavaScript at compile time JavaScript is an implementation of the ECMAScript standard, and it isn’t the only one–ActionScript is another well-known language based on the ECMAScript standard There are three versions of ECMAScript that you will come across when dealing with TypeScript ECMAScript 3 ECMAScript 3 was published... download and install the TypeScript for Visual Studio 2012 plug-in from the TypeScript language website at http://www.typescriptlang.org/ This will add TypeScript language support as well as new project and file templates You can add TypeScript files to an existing project, but for the examples in this book you can simply create a new project using the HTML Application with TypeScript template, which... Chapter 3 Type Safety Static, Dynamic, and Optional Types A statically typed language gives you compile-time checking for type safety This doesn’t mean you have to specify all types explicitly, as a smart compiler can infer the types in many cases TypeScript is no exception and the compiler will intelligently determine types for you even if you don’t explicitly declare the types in your code TypeScript... design-time tools and the compiler, no JavaScript code is generated from a TypeScript interface A TypeScript interface can extend multiple interfaces Class A TypeScript class is similar to a NET class and can contain functions and variables with varying levels of visibility In TypeScript you can use public and private visibility keywords on functions and variables A TypeScript class can extend one class and... any type You don’t have to rely on type inference in your code, and you can use type declarations to tell the compiler the intended type of a variable, function, or parameter in cases where it cannot work it out In the logging example, you only need to tell TypeScript the type of the message parameter in order for everything to be statically typed To declare a type, append a colon followed by the type. .. from https://bitbucket.org/syncfusion/typescript -succinctly Notes There are notes that highlight particularly interesting information about a language feature, including potential pitfalls you will want to avoid Note: An interesting note about TypeScript 12 Chapter 1 Concepts in TypeScript Code organization I will begin by drawing some parallels between NET and TypeScript in respect to code organization... statically typed In cases where the type cannot be inferred, the compiler doesn’t show an error as it would in NET, but instead treats the variable as a dynamic type, which in TypeScript is indicated with the any keyword I will discuss this in more detail in Chapter 3, "Type safety." Enumeration Enumerations in TypeScript are similar to NET enumerations The experimental implementation in version 0.8 of TypeScript... converting TypeScript into JavaScript, and raising errors and warnings it discovers The final stage involves the runtime executing the generated JavaScript 16 Figure 2: TypeScript life cycle 17 Chapter 2 Visual Studio This chapter describes how to set up Visual Studio 2012 for TypeScript If you are using a different development environment, you can skip this chapter There are more details on using TypeScript... Use Types at the end of this chapter Built-in Types TypeScript has five built-in primitive types as well as the dynamic any type and the void return type The any type can have any value assigned to it, and its type can be changed at runtime, so it could be initialized with a string and later overwritten with a number, or even a custom type The void return type can only be used to declare that a function . match your TypeScript code. There is currently no release date planned for ECMAScript 6, and it doesn’t support all of the concepts in the TypeScript language. TypeScript Life Cycle The TypeScript. plug-in from the TypeScript language website at http://www.typescriptlang.org/. This will add TypeScript language support as well as new project and file templates. You can add TypeScript files. visibility. In TypeScript you can use public and private visibility keywords on functions and variables. A TypeScript class can extend one class and implement multiple interfaces. Function A TypeScript