34,79 €
Writing clean, object-oriented code in JavaScript gets trickier and complex as the size of the project grows. This is where Typescript comes into the picture; it lets you write pure object-oriented code with ease, giving it the upper hand over JavaScript. This book introduces you to basic TypeScript concepts by gradually modifying standard JavaScript code, which makes learning TypeScript easy for C# ASP.NET developers.
As you progress through the chapters, you'll cover object programming concepts, such as classes, interfaces, and generics, and understand how they are related to, and similar in, both ES6 and C#. You will also learn how to use bundlers like WebPack to package your code and other resources. The book explains all concepts using practical examples of ASP.NET Core projects, and reusable TypeScript libraries. Finally, you'll explore the features that TypeScript inherits from either ES6 or C#, or both of them, such as Symbols, Iterables, Promises, and Decorators.
By the end of the book, you'll be able to apply all TypeScript concepts to understand the Angular framework better, and you'll have become comfortable with the way in which modules, components, and services are defined and used in Angular. You'll also have gained a good understanding of all the features included in the Angular/ASP.NET Core Visual Studio project template.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 543
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Aaron LazarAcquisition Editor: Alok DhuriContent Development Editor: Zeeyan PinheiroTechnical Editor: Ruvika RaoCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Rekha NairGraphics: Alishon MendonsaProduction Coordinator: Nilesh Mohite
First published: October 2018
Production reference: 1301018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-028-7
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Francesco Abbruzzese is an author of the MVC Controls Toolkit. He has also contributed to the diffusion and evangelization of the Microsoft web stack since the first version of ASP.NET MVC through tutorials, articles, and tools.
He writes about .NET and client-side technologies in his blog, dotnet-programming, and various online magazines/blogs. Now, his company, mvc-controls, implements and offers web applications, AI software, SAS products, tools, and services for web technologies associated with the Microsoft stack.
He moved from AI systems, where he implemented one of the first decision support systems for banks and financial institutions, to the video games arena, with top-ten titles such as Puma Street Soccer.
Michele Aponte has been passionately programming since 1993. She has worked as a Java, .NET, and JavaScript programmer for an Italian software house and numerous IT consulting companies. In 2013, she founded Blexin, with the aim of training users to migrate from their old solutions to new technologies. Michele believes in the value of sharing, and founded DotNetCampania, a Microsoft user group for which she organized many regional conferences for free, and even received recognition in the form of the MVP award.
You'll find Michele speaking at the most important Italian conferences on Microsoft and JavaScript technologies.
Parth Ghiya loves technologies and enjoys learning new things and facing the unknown. He has shown his expertise in multiple technologies, including mobile, web, and enterprise. He has been heading up projects in all domains with regard to security, high availability, and CI/CD. He has provided real-time data analysis, along with time-series and forecasting solutions.
In his spare time, he is an avid traveler, reader, and an immense foodie. He believes in technological independence and is a mentor, trainer, and contributor.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On TypeScript for C# and .NET Core Developers
Dedication
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Code in Action
Conventions used
Get in touch
Reviews
Introduction to TypeScript
Basics and installation
Adding types to JavaScript
Using JavaScript of the future now!
Installing the Visual Studio 2017 TypeScript SDK
Installation of Node.js-based TypeScript compiler
Adding TypeScript to your web projects
Your first TypeScript file
Running and debugging TypeScript code
TypeScript compiler options
Specifying parameters for the TypeScript compiler
TypeScript configuration file
Basic types
TypeScript type system
any and unknown
Strings, numbers, and Booleans
The null and undefined subtypes
Basics of union types
void
never
Enums
Declarations and scoping
Declarations
Obligatoriness of declarations and noImplicitAny
Variable scoping
Expressions – type assertions, and string interpolation
Summary
Questions
Further reading
Complex Types and Functions
Technical requirements
Arrays and tuples
Array declaration
Tuples
Interfaces and type inference
Interfaces basics
Readonly properties
Optional properties
Excess property check
Defining function properties in interfaces
Indexable types
Interface inheritance
Operations on types
Intersection types
Union types and type guards
Discriminated unions
Destructuring and spreads
Array destructuring
Array spreads
Tuples destructuring
Object destructuring
Object spreads
Functions
Anonymous functions and function types
Optional arguments and destructuring
Function overloads
Arrow functions
Summary
Questions
Further reading
DOM Manipulation
Technical requirements
DOM types
TypeScript predefined declarations
DOM basic types
HTML specific types
Basic DOM operations
DOM manipulation utilities
Removing an item
Adding a new item
Declaration files and JavaScript libraries
Where to find declaration files
How to use TypeScript declaration files
DOM operations with jQuery
Summary
Questions
Further reading
Using Classes and Interfaces
Technical requirements
Classes
Constructors
Members definition and modifiers
Implicit property definition
Accessors
Static members and static parts of a class
What is the type of a class object?
Inheriting from a class and implementing interfaces
Implementing interfaces
Inheriting from a class
Abstract classes and methods
Modular design with inheritance, interfaces, and abstract classes
Advanced type-compatibility
Summary
Questions
Further reading
Generics
Technical requirements
Generic functions and interfaces
A generic function for aggregating array elements
Generic classes
Generic constraints
Type constraints
Creating instances of generic variables
The keyof constraints
Summary
Questions
Namespaces and Modules
Technical requirements
Namespaces
DOM manipulation re-engineered with namespaces
Pitfalls of namespaces and ES6 modules
Exporting module symbols
Importing module symbols
Default export and import
Using ES6 modules in browsers
DOM manipulation re-engineered with modules
Loading modules
Compile-time and runtime module-resolution
Non-relative path module-resolution
Dynamic-loading module
Writing declaration files
Ambient modules
Automatic generation of declaration files
Summary
Questions
Further reading
Bundling with WebPack
Technical requirements
Bundling TypeScript and JavaScript
WebPack loaders – bundling TypeScript files
WebPack plugins – recovering the Visual Studio debugger
The WebPack module's resolution algorithm
Integrating WebPack in ASP.NET Core middleware
Watch mode and Hot Modules Replacement
Optimizing bundles
Library bundling – DllPlugin
Automatic common chunk extraction – SplitChunksPlugin
Dynamic loading
Production and development configurations
Bundling CSS, images, and HTML
Bundling images
Bundling HTML
Bundling CSS
Summary
Questions
Further reading
Building TypeScript Libraries
Technical requirements
Using VS Code
Building your library
Packaging your library as an npm package
Installing a test framework – Jasmine
Testing your library with Jasmine
Writing domlist library tests
Debugging tests
Summary
Questions
Further reading
Decorators and Advanced ES6 Features
Technical requirements
Symbols
Well-known symbols
Symbol.toStringTag
Symbol.toPrimitive
Symbol.search, Symbol.match, and Symbol.replace
Symbol.split
Iterators, iterables, and generators
Iterators and iterables
Generator functions and iterables
Inheriting from Array<T>
ECMAScript 2015 built-in iterables
Map<K, V> and WeakMap<K, V>
Set<T> and WeakSet<T>
Promises and async/await notation
fetch API
async/await notation
Decorators and metadata
Class decorators
Decorator factories
JavaScript built-in metadata – PropertyDescriptor
Method and accessor decorators
Handling metadata with the reflect-metadata polyfill
Parameter decorators
Property decorators
Automatic generation of metadata
Summary
Questions
Further reading
Angular ASP.NET Core Project Template
Technical requirements
Creating an Angular project
Project structure
The main application folder
Angular architecture
How Angular updates the HTML rendered by component templates
Modules, components, and data binding
Template bindings
Style and class bindings
Events and two-way bindings
Angular modules
Configuring and building an Angular application
Building and serving the application
Summary
Questions
Input and Interactions
Technical requirements
Template life cycle events
Angular lifetime events
How to handle Angular life cycle hooks
Using a Bootstrap modal in Angular
Angular update events
Component interaction
Custom two-way bindings
Forms
Pipes
Defining custom pipes
Application localization
Summary
Questions
Further reading
Angular Advanced Features
Technical requirements
Attribute directives
Defining max, min, and step validation attributes
Content projection and structural directives
The inputError directive
Predefined structural directories
Animations
Triggers, states, and state transitions
Parallel and child animations
Summary
Questions
Navigation and Services
Technical requirements
Services and Dependency Injection
Angular injectors' hierarchy
Service providers
Injecting localized error messages
Providers with the same token
Client-server communication
Sending data to the server
Communication progress events
Preventing XSRF attacks
Interceptors
Routing and navigation
Required and optional parameters
Improving routes
Children routes and named router-outlets
Guards
Lazy loaded modules
Testing
Summary
Questions
Further reading
Assessments
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Other Books You May Enjoy
Leave a review - let other readers know what you think
JavaScript was initially conceived to enrich server-generated HTML pages with JavaScript widgets, including date pickers, autocomplete, tabs, and so on. With the increase in available internet bandwidth, and the enhanced computational power of desktops, laptops, mobile devices, and smartphones, in order to ensure faster responses to all user inputs, and to be in a position to better exploit all available resources, increasingly, application logic moved from the server-side to JavaScript code on the client machine. This was the case until the diffusion of single-page applications, where the entire application logic runs in JavaScript on the client machine and the server's role is limited to handling shared data, as well as authentication/authorization logic.
The increasing complexity of JavaScript code bases led to the definition of new JavaScript specifications and toolsets to bring JavaScript from the level of a scripting language to that of modern object-oriented languages, such as Java, C#, and C++. Among the significant changes and tools, the following are worthy of mention:
The new ECMAScript 6 specifications that turn JavaScript into an advanced object-oriented language.
The new TypeScript language that adds types to JavaScript to enable better compilation-time checks, and implements almost all new ECMAScript 6 features that are not yet supported by all browsers. What makes TypeScript great is that it is JavaScript of the future plus types, and that it transpiles to browser-compatible JavaScript.
JavaScript library repositories, such as NPM, that are capable of
automatically
tracking dependencies among libraries.
JavaScript test frameworks, such as Jasmine.
The organization of JavaScript code into modules, and the usage tools called bundlers that facilitate the linking of several interdependent modules into a few JavaScript files to add to each HTML page.
Frameworks, such as Angular, that contain everything needed to implement single-page applications.
Somewhat unfortunately, knowledge of these subjects is spread across a variety of locations, so it is very frustrating when you come to write modern rich-client web applications. For instance, if you decide to learn Angular, you'll discover that you need to learn TypeScript beforehand, and then you'll discover that a knowledge of TypeScript is not enough either, because you also need to learn more about ECMAScript 6 and JavaScript modules. Finally, if you have resisted hitherto, you'll discover that you also need to learn about bundling and WebPack.
This book consolidates in a single place all the knowledge you require to implement a modern rich-client web application using a non-trivial JavaScript/TypeScript code base—TypeScript, ECMAScript 6 features, JavaScript modules, TypeScript library development and testing, bundling modules with WebPack, and the Angular single-page application framework.
This book was conceived mainly for ASP.NET developers who want to start developing rich-client applications using non-trivial TypeScript code bases. This book explains how to improve classic server-based web applications using well architected TypeScript code bases, and also how to build modern single-page applications in TypeScript with ASP.NET Core and Angular.
While the last part of the book focuses on Angular, the book covers TypeScript, ECMAScript 6 JavaScript features, JavaScript modules, and WebPack bundler, these being the starting points for learning any other single page application framework/library, such as React, Vue.js, Knockout.js, Aurelia, and Meteor. Hence, this book is also a useful tool for any ASP.NET developer who would like to learn any of the preceding frameworks/libraries, but who lacks some basic knowledge to embark on this learning path.
While most of the chapters use Visual Studio ASP.NET Core project templates, the book only requires a basic knowledge of Visual Studio, and C#, so it can be read by any web developer with a basic knowledge of ES5 JavaScript, a basic knowledge of any modern object-oriented language, such as C#, C++, or Java, and a basic knowledge of either Visual Studio or any another similar IDE.
Chapter 1, Introduction to TypeScript, explains how to install and configure TypeScript transpiler, TypeScript base types, variable declarations, and scoping. It also discusses TypeScript's mission, and how TypeScript types can help you to write, debug, and maintain your code bases.
Chapter 2, Complex Types and Functions, explains the basics of the language: arrays, tuples, interfaces, and function declarations. It also explains how to define new types by performing operations on existing types, and how to simplify your code with ECMAScript 6 destructuring and spread.
Chapter 3, DOM Manipulation, covers TypeScript types used to describe and manipulate the DOM, and how to use JavaScript libraries such as jQuery from TypeScript.
Chapter 4, Using Classes and Interfaces, covers TypeScript object programming, classes, interfaces, inheritance, and interface implementations. A complete code example explains how to architect a modular application with the help of abstract classes, interfaces, and inheritance.
Chapter 5, Generics, covers TypeScript generics, and how to define constraints on generics and type-mappings based on generics. TypeScript generics mimic C# generics, but, like C++ generics, they disappear in the compiled code.
Chapter 6, Namespaces and Modules, covers TypeScript's modular organization of code based either on namespaces, or on ECMAScript 6 modules. While TypeScript modules are completely based on ECMAScript 6 modules, they may run also in environments that do not support ECMAScript 6 modules, since ECMAScript 6 syntax may be processed by JavaScript bundlers such as WebPack, or transpiled in the syntax of AMD, CommonJS, or SystemJS loaders, that run on all platforms/browsers.
Chapter 7, Bundling with WebPack, contains a quite complete and practical description of WebPack, and of its more frequently used modules and loaders. Here, the reader can learn everything that is worth knowing in terms of using WebPack with most modern JavaScript frameworks/libraries.
Chapter 8, Building TypeScript Libraries, describes how to develop a TypeScript library package with Visual Studio Code, how to test it with Jasmine, and how to package it as an npm package.
Chapter 9, Decorators and Advanced ES6 Features, covers all ECMAScript 6 features, such as Symbols, Iterators/Generators, and Promises, that were not covered in previous chapters. The chapter also covers TypeScript's async/await notation, which is transpiled to Promise-based code, and TypeScript decorators and metadata that are important Angular building blocks.
Chapter 10, Angular ASP.NET Core Project Template, introduces Angular architecture, and describes all the parts an Angular CLI project is composed of, and how to configure a project. The chapter then lists all Angular building blocks, focusing on modules, components, and data binding.
Chapter 11, Input and Interactions, explains how to take and validate user input, and how to customize standard data binding behavior with pipes and life cycle hooks. The chapter also covers the interaction of components through JavaScript and custom events.
Chapter 12, Angular Advanced Features, covers the details of attribute and structural directive usage and definition. The chapter also explains how to customize components with content projection (that is, filling predefined holes with input content), and how to improve the user interface with Angular animations, giving all details of Angular animation syntax.
Chapter 13, Navigation and Services, covers all Angular features conceived for complex applications, navigation among application pages, and how to dynamically load Angular modules. It also covers how components can communicate with the server using Angular HTTP Client class, and how HTTP Client and other services can be injected into components' constructors with the help of dependency injection. It also describes how to test components and other Angular classes.
We would be needing the Visual Studio Community edition (version 15.8.7 or higher) software and Visual Studio Code (version 1.28 or higher).
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Hands-On-TypeScript-for-CSharp-and-.NET-Core-Developers. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/9781789130287_ColorImages.pdf.
Visit the following link to check out videos of the code being run: http://bit.ly/2RlN1Yw.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The name, surname, and secondName variables are public properties, while fullName is a public method."
A block of code is set as follows:
class Person { name: string; surname: string; secondName?: string; fullname(): string { return this.secondName !== undefined ? this.name + " " + this.secondName + " " + this.surname : this.name + " " + this.surname; }
Any command-line input or output is written as follows:
npm install <package name>@<package version>
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Right-click on the domlist folder and select Open with Code."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
The implementation of large JavaScript code bases in modern, rich client web applications has alwayspushed more in the direction of preventing hard-to- find bugs, with exhaustive checking at compile time. TypeScript meets this requirement by transforming JavaScript into a strongly typed language; that is, into a language that requires declarations and type specifications for all variables and properties. In fact, strong typing allows compile-time type checking that prevents the misuse of variables and functions while variable declarations avoid the variable names misspelling that often causes these bugs in JavaScript.
This chapter explains the TypeScript manifest, how to install it and add it to your ASP.NET core projects, how to organize files and compile them to JavaScript, and the basics of TypeScript configuration. Then the chapter introduces the basics of types and variable declarations.
The following topics will be covered in this chapter:
Installation on Windows and the TypeScript mission
Adding TypeScript to ASP.NET core web projects and debugging it
Basics of TypeScript configuration
Simple types, enums, and basics of Union types
Variable declarations, scoping, expressions, casting, and string interpolation
This section discusses the main motivations behind TypeScript and how to install the TypeScript SDK. Installation concerns just developers' machines since TypeScript code is completely compiled into JavaScript code and doesn't need any runtime library to be executed.
While TypeScript was initially conceived to perform better compile-time checks than JavaScript, very soon its mission was extended to mitigate the different support for new JavaScript standards which are at the moment, ECMAScript 6-8. TypeScript includes most of ECMAScript 6-8's important features, but you may target the transpiled code at previous JavaScript versions. When a feature is not available in the target JavaScript version, the TypeScript transpiler creates code that simulates this feature in the target JavaScript version.
For instance, TypeScript includes ECMAScript 6 classes that will be covered in Chapter 4, Using Classes and Interfaces, and ECMAScript 8 async/await, which will be covered in the Promises and async/await notation section of Chapter 9, Decorators and Advanced ES6 Features. Here is an example of async/await use:
async
function
asyncAwaitExample
(url: string): string
{
let response= await fetch(url
);
return await response.text()
; }
The syntax is completely analogous to C# async/await.
As a default, Visual Studio 2017 installers automaticallyinstall TypeScript SDK, and as long as you keep Visual Studio updated, you should always have a recent version of the TypeScript SDK. Anyway, if for some reason TypeScript was not installed, or if you want to be sure you have the latest version of the TypeScript SDK, proceed as follows.
Go to Program and Functionalities in your computer's Control Panel and verify that TypeScript SDK is installed, and which version is installed:
In this case, TypeScript is already installed and its version is 2.8.3.0.
Open Visual Studio 2017 and go to Tools | Extensions and Updates:
When the Extensions and Updates window opens, in the left-hand menu, select Online | Visual Studio Gallery | Tools, and then type TypeScript in the text box in the upper-right corner.
A few seconds after you finish typing TypeScript, you should see all available versions of the TypeScript SDK. Select the most recent version:
In this case, the most recent version is 2.8.3.
If the version you found is more recent than the one already installed, click on the list item to select it, and then click on the Download button that appears to download the TypeScript SDK installer. When the download completes, double-click on the installer to install the SDK.
In the Using VS Code section of Chapter 8, Building Typescript Libraries, we will learn TypeScript development without Visual Studio. In this case, we need the Node.js-based TypeScript compiler that is independent of Visual Studio.
As a first step, go to the Node.js website at https://nodejs.org/en/ and download the recommended version of Node.js.
Once installation is complete, open a Windows Command Prompt and type node -v to verify Node.js has been installed properly, and to verify its version.
We also need npm, the Node.js packages handler (a kind of NuGet for Node.js packages). npm is automatically installed with Node.js. Type npm -v in the Windows Command Prompt to verify its proper installation and its version.
Here is the result of typing these commands in a Windows Command Prompt:
Now, installing TypeScript compiler is quite easy; just typenpm install -g typescript. This will install the last version of the TypeScript compiler globally on your computer.
If you need a different version of the TypeScript compiler for a specific project, you may install it locally for that project folder, while all other projects will continue using the version installed globally. This can be done as follows:
Open Command Prompt in the project folder.
Suppose the version you would like to install is 2.7.1, then type the following command:
npm install --save-dev [email protected]
Once you have the TypeScript SDK installed, adding a TypeScript code file to an ASP.NET Core project is straightforward. Your TypeScript file will be compiled in a JavaScript file that you may call, as usual, in any View. However, you may debug your code and put breakpoints directly in the TypeScript source.
Running and debugging TypeScript code is straightforward. It is enough to add the transpiled JavaScript file to a view. Let's add our previous test.js file to the bottom of the Home/Index.cshtml view:
@section Scripts{ <script src="~/ts/tests.js"></script>}
It is worth remembering that Script is a section defined in the Layout view of the ASP.NET Core MVC template. It allows all views to place the JavaScript code they need in the right place in the Layout view. When you run the project, an alert box should appear as soon as the website's default page is loaded in the browser, as shown in the following screenshot:
Thanks to the test.js.map map file generated by the TypeScript compiler, it is possible to debug the TypeScript source instead of the JavaScript transpiled code. In fact, map files contain all the information needed to map each position in the transpiled file into a position in the source file. Map files are not a peculiarity of TypeScript but a well-recognized standard, since they are alsoused for mapping minimized JavaScript files to their sources.
Let's place a breakpoint on the last instruction of test.ts and run the project:
Once the breakpoint is hit, you may benefit from all the Visual Studio debugging features you are used to when debugging C# code.
You may see values by hovering over variables with the mouse:
Or, you can use a Watch 1 window:
You also have access to the calls stack, to an immediate window, to the intellitrace, and to all other C# code features you are used to.
As a default, Visual Studio compiles all TypeScript files in your project into JavaScript files with the same names, but with the .js extension, and they are placed in the same folder. Moreover, for each .js file, it creates a file with the same name but with a .js.map extension that is called a map file. Map files map locations in the generated JavaScript files to locations in their TypeSctipt sources, thus enabling debugging on the TypeScript sources. This default behavior of the TypeScript compiler may be changed in two ways: either by forcing Visual Studio to invoke the TypeScript compiler with different parameters, or by specifying the desired options in a configuration file.
All parameters Visual Studio uses to invoke the TypeScript compiler may be edited in the project properties by right-clicking on the project icon and selecting Properties:
In the window that appears, select TypeScript Build. Here, you may change several options:
The
TypeScript version
from the ones installed.
The
ECMAScript version
of the JavaScript code generated. At
the
moment,
ECMAScript 5
is supported by all mainstream browsers, while higher versions have incomplete support, so it is the advised choice for most applications.
Whether to
compile on save
or not. If this option is deselected, TypeScript files are compiled only when the whole project is built. This possibility may be useful in complex projects in which
the
TypeScript build is quite slow because after transpilation, large
files are first minimized and then bundled into chunks.
To keep, or not, all TypeScript source comments in the generated JavaScript files.
To choose a different directory for both the JavaScript and map files created by the compiler.
To emit JavaScript code, or not, in
the
case of errors.
To emit map files or not. If you want to debug TypeScript sources, you should always emit map files.
The directory in which to look for TypeScript files to compile. If this directory is not provided, the project root is taken.
Let's unselect the Compile on save option, save the changes, modify something in the test.ts file (for instance, change the Hello string to Hello world), and verify that the file is not compiled on save. Have a look at the last modification date of the test.js file. After this test, do not forget to select the Compile on save optionagain.
Now, let's try to put all the files generated by the TypeScript compiler in the js folder:
After that, if you change something in the test.ts file and save it, test.js and test.js.map will appear in the .js folder:
A TypeScript configuration file allows us to specify several more options. We may specify several input directories instead of just one, we may specify paths/files to be excluded from compilation, or we may specify several more compilations flags.
If you want Visual Studio to invoke the TypeScript compiler automatically, you must give the project TypeScript configuration file its default name, which, tsconfig.json. Otherwise, you must invoke the TypeScript compiler manually and pass it the configuration file name as a command-line parameter.
In order to add a TypeScript configuration file to your project, right-click on the project icon in the project explorer and select Add New Item:
Then select TypeScript JSON Configuration File. The configuration file should appear in the project root. Replace its content with the following code:
{ "compileOnSave": true, "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "outDir": "wwwroot/js" }, "include": [ "wwwroot/ts/**/*.ts" ], "exclude": [ "**/node_modules" ]}
compileOnSave enables compilation on save, while compilerOptions contains all compiler flags. It is easy to recognize the same options we discussed previously:
noEmitOnError
: No code generation in
the
case of errors.
removeComments
: It removes/keeps comments in JavaScript-emitted code.
sourceMap
:
It enables/disables map files.
target
: It specifies the JavaScript version of the emitted code; in our case, ECMAScript 5.
outDir
: It specifies where to place the emitted files. If omitted, this is next to their sources.
noImplicitAny
: It will be discussed later on in this chapter.
Intellisense suggests the allowed options and values, so there is no need to remember their exact names.
include specifies a list of directory or file patterns to include in the compilation. Each entry is a pattern that may match several directories/files, since entries may contain wildcards: * matches a single name, while ** matches any path. In our case, there is a single pattern that selects all files contained in wwwroot/ts and in all its subdirectories (because of the **), whose extension is .ts.
exclude specifies a list of patterns to remove from the ones added within other options (for instance, with the include option). In our case, a unique pattern excludes all files contained in any directory called node_modules located at any depth, since these directories usually include JavaScript packages downloaded with the NPM Package Manager.
There is also a files option to add a list of files (just files, not patterns) to the compilation:
"files":[ "file1.ts", "dir/file2.ts", ...]
If no files or include options are specified, the whole project root is taken.
Save tsconfig.json and modify tests.ts. When the file is saved, it should be compiled according to the options contained in tsconfig.json.
Once a tsconfig.json has been added, all options in the TypeScript Build panel of the project properties are disabled:
You may use this panel just to select the TypeScript version; that is, the compiler that is automatically invoked by Visual Studio. All other options must be specified in the configuration file you added.
TypeScript primitive types obviously include JavaScript primitive types, namely Boolean, number, string, null, and undefined. However, TypeScript adds a few new primitive types and slightly changes the semantics of primitive types. All type declaration examples in the remainder of the chapter may be tested by adding them to our test.ts file.
While any may be considered the TypeScript root type, the semantics of any are quite different from the usual semantics of other languages' root types. In fact, while other languages' root types allow almost no operations on them, any allows all operations. It is a way to prevent any type check, and was conceived this way to allow compatibility of some code chunks with JavaScript. In fact, once something has been declared as any, it may be processed as it can in simple JavaScript, with no preoccupations about compilation-time type checks.
TypeScript 3.0 alsointroduces theunknowntype, which behaves more like a usual root type since no operations are allowed on a variable declared asunknown, and all values may be assigned to an unknown variable. Thus, from version 3.0 onward, TypeScript has two root types that can be assigned to each other,anyandunknown.anydisables type checks and allows all operations, whileunknownbehaves like a usual root type.
void is a type that can't assume any value except for null or undefined. It make no sense to declare a variable of type void. This type should be used just to declare a function that must return no value:
function sayHello(): void { alert("Hello world");}
If a function whose return value has been declared void actually returns a value along some paths, an error is signaled at compile time:
/* Wrong! */function sayHelloWrong(): void { alert("Hello world"); return 1;}
Also, the converse is true; a function whose return type has been declared, say number, but which doesn't return a value along some paths, will trigger a compile-time error:
/* Wrong! */function wrongNumer(x: number): number { if (x > 0) return x;}
The error may be removed either by adding the missing return statement or by adding void to the return value:
/* Correct! */function wrongNumer(x: number): number|void { if (x > 0) return x;}
TypeScript declarations and scoping rules are one of the ECMAScript 6 version of JavaScript, with the only addition of type specifications after the declared objects. Also, TypeScript expressions support some new ECMAScript 6 features, such as string interpolation. In case the JavaScript target is a lower version, all ECMAScript 6-specific features are simulated by the TypeScript transpiler, which automatically generates the equivalent JavaScript code.
In JavaScript, when an undeclared variable is used, it is automatically declared in global scope, often causing hard-to-find bugs.
For this reason, in TypeScript, variables can be used just after they have been declared:
When a variable is initialized, its type may be automatically inferred, so it may be omitted:
However, when a variable is not initialized, the specification of the variable type is not obligatory! The type assigned to a not initialized variable when the type is not specified explicitly depends on the noImplicitAny compiler option, or, more specifically:
When
noImplicitAny
i
s
false
, the variable is assigned the
any
type.
When
noImplicitAny
is
true
, the compiler tries to infer the type of the variable from the type of the first expression that is assigned to that variable.
For example, if the configuration file of the TypeScriptTests project sets noImplicitAny to false and we omit type specifications:
var untypedVar;
any is assumed, as you may verify by hovering the mouse over the untypedVar variable:
However, if you set noImplicitAny to true in tsconfig.json, and you slightly change the code:
The number typeis automatically inferred because the first value assigned tountypedVaris anumber (namely,1.2). Thus, no error is signaled in the next statement, in which untypedVar is added to a constant number.
