Mastering TypeScript 3
eBook - ePub

Mastering TypeScript 3

Build enterprise-ready, industrial-strength web applications using TypeScript 3 and modern frameworks, 3rd Edition

Nathan Rozentals

Share book
  1. 694 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Mastering TypeScript 3

Build enterprise-ready, industrial-strength web applications using TypeScript 3 and modern frameworks, 3rd Edition

Nathan Rozentals

Book details
Book preview
Table of contents
Citations

About This Book

Master the TypeScript language and its latest features. Explore modern application frameworks and utilize industry best practices in TDD, OOP and UI Design.

Key Features

  • Learn the key features of TypeScript 3 and explore advanced language features through in-depth discussions.
  • Use TypeScript with modern frameworks including Backbone, Angular, Aurelia, React, and Node.
  • Explore TDD practices, OOP techniques, and industry best practices to create high-quality, modular, and adaptable applications.

Book Description

TypeScript is both a language and a set of tools to generate JavaScript. It was designed by Anders Hejlsberg at Microsoft to help developers write enterprise-scale JavaScript.

Starting with an introduction to the TypeScript language, before moving on to basic concepts, each section builds on previous knowledge in an incremental and easy-to-understand way. Advanced and powerful language features are all covered, including asynchronous programming techniques, decorators, and generics.

This book explores many modern JavaScript and TypeScript frameworks side by side in order for the reader to learn their respective strengths and weaknesses. It will also thoroughly explore unit and integration testing for each framework.

Best-of-breed applications utilize well-known design patterns in order to be scalable, maintainable, and testable. This book explores some of these object-oriented techniques and patterns, and shows real-world implementations.

By the end of the book, you will have built a comprehensive, end-to-end web application to show how TypeScript language features, design patterns, and industry best practices can be brought together in a real-world scenario.

What you will learn

  • Gain insights into core and advanced TypeScript language features
  • Integrate existing JavaScript libraries and third-party frameworks using declaration files
  • Target popular JavaScript frameworks, such as Angular, React, and more
  • Create test suites for your application with Jasmine and Selenium
  • Organize your application code using modules, AMD loaders, and SystemJS
  • Explore advanced object-oriented design principles
  • Compare the various MVC implementations in Aurelia, Angular, React, and more

Who this book is for

This guide to the TypeScript that starts with basic concepts, and then builds on this knowledge to introduce more advanced language features and frameworks. No prior knowledge of JavaScript is required, although some prior programming experience is assumed. If you are keen to learn TypeScript, this book will give you all of the necessary knowledge and skills to tackle any TypeScript project. If you are already an experienced JavaScript or TypeScript developer, then this book will take your skills to the next level. Learn how to use TypeScript with a multitude of modern frameworks, and choose the best framework for your project requirements. Investigate techniques for Test Driven Development, explore industry-standard design patterns, and learn how to put together a full production-ready TypeScript application.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Mastering TypeScript 3 an online PDF/ePUB?
Yes, you can access Mastering TypeScript 3 by Nathan Rozentals in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming. We have over one million books available in our catalogue for you to explore.

Information

Year
2019
ISBN
9781789537475
Edition
3

Types, Variables, and Function Techniques

TypeScript introduces strong typing to JavaScript through a simple syntax, referred to by Anders Hejlsberg as syntactic sugar. This sugar is what assigns a type to a variable. This strong typing syntax, which is officially called type annotation, is used wherever a variable is used. In other words, we can use type annotation in a variable declaration, a function parameter, or to describe the return type of a function itself.
As we discussed in Chapter 1, TypeScript – Tools and Framework Options, there are many benefits to enforcing types in a development language. These include better error checking, the ability for an IDE to provide more intelligent code suggestions, and the ability to introduce object-oriented techniques into the coding experience.
The TypeScript language uses several basic types, such as number and boolean, and also uses a few common rules to identify the type of a variable. Understanding these rules and applying them to your code is a fundamental skill when writing TypeScript code.
Along with these basic rules, the TypeScript compiler also adopts ES6 syntax to allow for more advanced object manipulation. This chapter introduces these basic types, the rules that the compiler uses for type checking, and then explores advanced object manipulation.
We will cover the following topics in this chapter:
  • Basic types and type syntax—strings, numbers, and booleans
  • Inferred typing and duck typing
  • Template strings
  • Arrays, and using for...in and for...of
  • The any type and explicit casting
  • Enums
  • The const and let keywords
  • Definite assignment and dotted property types
  • Functions and anonymous functions
  • Function parameters
  • Function callbacks, function signatures, and function overrides
  • Try catch
  • Advanced types, including union types, type guards, and type aliases
  • The never and unknown types
  • Object rest and spread
  • Tuples
  • Bigint
If you already have experience with TypeScript and have a good understanding of the language, then you can have a quick read through the entire chapter. Otherwise, you can skip on to the later parts of the chapter, where more advanced types, such as never, are explored.

Basic types

JavaScript, by nature, is described as a dynamically typed language. This means that any particular variable can hold a number of data types, including numbers, strings, arrays, objects, and functions. The type of a variable in JavaScript is determined by assignment. This means that when we assign a value to a variable, the JavaScript runtime interpreter determines the type of that variable.
However, the JavaScript runtime can also reassign the type of a variable depending on how it is being used, or on how it is interacting with other variables. It may assign a number to a string, for example, in certain cases.
Let's take a look at an example of this dynamic typing in JavaScript and what errors it can introduce. Then, we will explore the strong typing that TypeScript uses and its basic type system.

JavaScript typing

As we saw in Chapter 1, TypeScript - Tools and Framework Options, JavaScript objects and variables can be changed or reassigned on the fly. As an example of this, consider the following JavaScript code:
function doCalculation(a,b,c) { return (a * b) + c; } var result = doCalculation(2,3,1); console.log('doCalculation():' + result); 
Here, we have a doCalculation function that is computing the product of the arguments a and b, and then adding the value of c. We are then calling the doCalculation function with the arguments 2, 3, and 1, and logging the result to the console. The output of this sample would be as follows:
doCalculation():7
This is the expected result as 2 * 3 = 6, and 6 + 1 = 7. Now, let's take a look at what happens if we inadvertently call the function with strings instead of numbers:
result = doCalculation("2","3","1"); console.log('doCalculation():' + result); 
The output of this code sample is as follows:
doCalculation():61
The result of 61 is very different from our expected result of 7. So what is going on here?
If we take a closer look at the code in the doCalculation function, we start to understand what JavaScript is doing with our variables and their types.
The product of two numbers, that is, (a * b), returns a numeric value; so JavaScript is automatically converting the 2 and 3 values to numbers in order to compute the product and is correctly computing the 6 value. This is a particular rule that JavaScript applies when it needs to convert strings to numbers, and comes into play when the result of a calculation should be a number. The addition symbol, (+), however, can be used with numbers as well as strings. Because the argument c is a string, JavaScript is converting the 6 value into a string in order to add two strings. This results in the 6 string being added to the 1 string, which results in the 61 value.
This code snippet is an example of how JavaScript can modify the type of a variable based on how it is used. This means that to effectively work with JavaScript, we need to be aware of this sort of type conversion, and understand when and where this conversion could take place. Obviously, these sorts of automatic type conversions can cause unwanted behavior in our code.

TypeScript typing

TypeScript, on the other hand, is a strongly typed language. Once you have declared a variable to be of a certain type, you cannot change it. As an example, if you declare a variable to be of type string, then you can only assign string values to it, and any instance of this variable can only treat it as though it has a type of string. This helps to ensure that code that we write will behave as expected. When we know immediately that the value of a variable will always be a string, we will know which of these conversion rules JavaScript will use.
JavaScript programmers have always relied heavily on documentation to understand how to call functions, and the order and type of the correct function parameters. But what if we could take all of this documentation and include it within the IDE?
Then, as we write our code, our compiler could point out to us—automatically—that we were using variables or functions in a JavaScript library in the wrong way. Surely this would make us more efficient, more productive programmers, and allow us to generate better code with fewer errors?
TypeScript does exactly that. It introduces a very simple syntax to define the type of a variable in order to ensure that we are using it in the correct manner. If we break any of these rules, the TypeScript compiler will automatically generate errors, pointing us to the lines of code that are in error.
This is how TypeScript got its name. It is JavaScript with strong typing, hence TypeScript. Let's take a look at this very simple language syntax that enables the Type in TypeScript.

Type syntax

The TypeScript syntax for declaring the type of a variable is to include a colon (:) after the variable name, and then indicate its type. As an example of this, let's rewrite our problematic doCalculation function to only accept numbers. Consider the following TypeScript code:
function doCalculation( a : number, b : number, c : number) { return ( a * b ) + c; } var result = doCalculation(3,2,1); console.log("doCalculation():" + result); 
Here, we have specified that the doCalculation function needs to be invoked with three numbers. This means that the properties a, b, and c must be of type number in order to call this function. If we now attempt to call this function with strings, as we did with the JavaScript sample, as follows:
var result = doCalculation("1", "2", "3"); console.log("doCalculation():"" + result); 
The TypeScript compiler will generate the following error:
error TS2345: Argument of type '"1"' is not assignable to parameter of type 'number'.
This error message clearly tells us that we cannot pass a string into our function, where a numeric value is expected.
To further illustrate this point, consider the following TypeScript code:
var myString : string; var myNumber : number; var myBoolean : boolean; myString = "1"; myNumber = 1; myBoolean = true; 
Here, we are telling the compiler that the myString variable is of type string, even before the variable itself has been used. Similarly, the myNumber variable is of type number, and the myBoolean variable is of type boolean. TypeScript has introduced the string, number, and boolean keywords for each of these basic JavaScript types.
If we then attempt to assign a value to a variable that is not of the same type, the TypeScript compiler will generate a compile-time error. Given the variables declared in the preceding code, consider the following TypeScript code:
myString = myNumber; myBoolean = myString; myNumber = myBoolean; 
This is what happens after our attempt to mix these basic types:
The TypeScript compiler has now started generating compile errors because it has detected that we are attempting to mix these basic types:
  • The first error is generated because we cannot assign a number value to a variable of type string
  • Similarly, the second compile error indicates that we cannot assign a string value to a variable of type boolean
  • And the third error is generated because we cannot assign a boolean value to a variable of type number
The strong typing syntax that the TypeScript language introduces means that we need to ensure that the types on the left-hand side of an assignment operator (=) are the same as the types on the right-hand side of the assignment operator.
To fix the preceding TypeScript code and remove the compile errors, we would need to do something similar to the following:
myString = myNumber.toString(); myBoolean = (myString === "test"); if (myBoolean) { myNumber = 1; } 
Here, our first line of code has been changed to call the .toString() function on the myNumber variable (which is of type number), in order to return a value that is of type string. This line of code, then, does not generate a compile error because both sides of the equal sign (or assignment operator) are strings.
Our second line of code has also been changed, so that the right-hand side of the assignment operator returns the result of a Boolean comparison, myString === "test", which wil...

Table of contents