Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

TypeScript Blueprints
TypeScript Blueprints
TypeScript Blueprints
Ebook560 pages3 hours

TypeScript Blueprints

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • This book will help you whether you’re a beginner or an expert
  • Complete and complex projects provide codes that are ready and solutions for start-ups and enterprise developers
  • The book will showcase the power and depth of TypeScript when it comes to high performance and scalability
Who This Book Is For

This book was written for web developers who wish to make the most of TypeScript and build fun projects. You should be familiar with the fundamentals of JavaScript, and basic knowledge of TypeScript is useful.

LanguageEnglish
Release dateJul 28, 2016
ISBN9781785888779
TypeScript Blueprints

Related to TypeScript Blueprints

Related ebooks

Programming For You

View More

Related articles

Reviews for TypeScript Blueprints

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    TypeScript Blueprints - Ivo Gabe de Wolff

    Table of Contents

    TypeScript Blueprints

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    Why subscribe?

    Free access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Downloading the color images of this book 

    Errata

    Piracy

    Questions

    1. TypeScript 2.0 Fundamentals

    What is TypeScript?

    Quick example

    Transpiling

    Type checking

    Learning modern JavaScript

    let and const

    Classes

    Arrow functions

    Function arguments

    Array spread

    Destructuring

    Template strings

    New classes

    Type checking

    Primitive types

    Defining types

    Undefined and null

    Type annotations

    Summary

    2. A Weather Forecast Widget with Angular 2

    Using modules

    Setting up the project

    Directory structure

    Configuring TypeScript

    Building the system

    The HTML file

    Creating the first component

    The template

    Testing

    Interactions

    One-way variable binding

    Event listeners

    Adding conditions to the template

    Directives

    The template tag

    Modifying the about template

    Using the component in other components

    Showing a forecast

    Using the API

    Typing the API

    Creating the forecast component

    Templates

    Downloading the forecast

    Adding @Output

    The main component

    Using our other components

    Two-way bindings

    Listening to our event

    Geolocation API

    Component sources

    Summary

    3. Note-Taking App with a Server

    Setting up the project structure

    Directories

    Configuring the build tool

    Type definitions

    Getting started with NodeJS

    Asynchronous code

    Callback approach for asynchronous code

    Disadvantages of callbacks

    The database

    Wrapping functions in promises

    Connecting to the database

    Querying the database

    Understanding the structural type system

    Generics

    Typing the API

    Adding authentication

    Implementing users in the database

    Adding users to the database

    Testing the API

    Adding CRUD operations

    Implementing the handlers

    Request handling

    Writing the client side

    Creating the login form

    Creating a menu

    The note editor

    The main component

    Error handler

    Running the application

    Summary

    4. Real-Time Chat

    Setting up the project

    Configuring gulp

    Getting started with React

    Creating a component with JSX

    Adding props and state to a component

    Creating the menu

    Testing the application

    Writing the server

    Connections

    Typing the API

    Accepting connections

    Storing recent messages

    Handling a session

    Implementing a chat message session

    Connecting to the server

    Automatic reconnecting

    Sending a message to the server

    Writing the event handler

    Creating the chat room

    Two-way bindings

    Stateless functional components

    Running the application

    Comparing React and Angular

    Templates and JSX

    Libraries or frameworks

    Summary

    5. Native QR Scanner App

    Getting started with NativeScript

    Creating the project structure

    Adding TypeScript

    Creating a Hello World page

    Creating the main view

    Adding a details view

    Scanning QR codes

    Type definitions

    Implementation

    Testing on a device

    Adding persistent storage

    Styling the app

    Comparing NativeScript to alternatives

    Summary

    6. Advanced Programming in TypeScript

    Using type guards

    Narrowing

    Narrowing any

    Combining type guards

    More accurate type guards

    Assignments

    Checking null and undefined

    Guard against null and undefined

    The never type

    Creating tagged union types

    Comparing performance of algorithms

    Big-Oh notation

    Optimizing algorithms

    Binary search

    Built-in functions

    Summary

    7. Spreadsheet Applications with Functional Programming

    Setting up the project

    Functional programming

    Calculating a factorial

    Using data types for expressions

    Creating data types

    Traversing data types

    Validating an expression

    Calculating expressions

    Writing unit tests

    Parsing an expression

    Creating core parsers

    Running parsers in a sequence

    Parsing a number

    Order of operations

    Defining the sheet

    Calculating all fields

    Using the Flux architecture

    Defining the state

    Creating the store and dispatcher

    Creating actions

    Adding a column or a row

    Changing the title

    Showing the input popup

    Testing actions

    Writing the view

    Rendering the grid

    Rendering a field

    Showing the popup

    Adding styles

    Gluing everything together

    Advantages of Flux

    Going cross-platform

    Summary

    8. Pac Man in HTML5

    Setting up the project

    Using the HTML5 canvas

    Saving and restoring the state

    Designing the framework

    Creating pictures

    Wrapping other pictures

    Creating events

    Binding everything together

    Drawing on the canvas

    Adding utility functions

    Creating the models

    Using enums

    Storing the level

    Creating the default level

    Creating the state

    Drawing the view

    Handling events

    Working with key codes

    Creating the time handler

    Running the game

    Adding a menu

    Changing the model

    Rendering the menu

    Handling events

    Modifying the time handler

    Summary

    9. Playing Tic-Tac-Toe against an AI

    Creating the project structure

    Configure TypeScript

    Adding utility functions

    Creating the models

    Showing the grid

    Creating operations on the grid

    Creating the grid

    Adding tests

    Random testing

    Implementing the AI using Minimax

    Implementing Minimax in TypeScript

    Optimizing the algorithm

    Creating the interface

    Handling interaction

    Creating players

    Testing the AI

    Testing with a random player

    Summary

    10. Migrate JavaScript to TypeScript

    Gradually migrating to TypeScript

    Adding TypeScript

    Configuring TypeScript

    Configuring the build tool

    Acquiring type definitions

    Testing the project

    Migrating each file

    Converting to ES modules

    Correcting types

    Adding type guards and casts

    Using modern syntax

    Adding types

    Refactoring the project

    Enable strict checks

    Summary

    TypeScript Blueprints


    TypeScript Blueprints

    Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

    First published: July 2016

    Production reference: 1250716

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham 

    B3 2PB, UK.

    ISBN 978-1-78588-701-7

    www.packtpub.com

    Credits

    About the Author

    Ivo Gabe de Wolff has been a freelance developer under the name of ivogabe since 2012 and he is studying mathematics and computing sciences at Utrecht University. When he was eleven he started programming in Game Maker. Currently, he uses TypeScript on a daily basis. Recently, he has used TypeScript in lots of different environments, including mobile apps, servers, and command-line tools. Now he mainly specializes in NodeJS programming.

    Furthermore, he is the author of various open source projects, including gulp-typescript. You can find his projects on github.com/ivogabe . If you want to read more about TypeScript, JavaScript, gulp, or Functional Programming, you can take a look at his blog at dev.ivogabe.com .

    It required a lot of work to compose this book. I could not have done this without the help of these people:

    The team at Packt Publishing and the reviewers of this book, because of their precise feedback and hard work. This has helped me a lot to improve the quality of this book.

    My fellow students, for brainstorming and helping on specific topics.

    My teachers at Utrecht University, for giving inspiration and challenging me on various topics. I especially want to thank Jurriaan Hage for supervising my thesis.

    Finally, my family, for their support and tips, even though they did not have knowledge on these topics. These people have helped me to to make the book as it now lies in front of you.

    About the Reviewer

    Matthew Hill is a British software developer with substantial experience in web application development. An established developer in the TypeScript and JavaScript spheres, he thoroughly enjoys working on open source projects and dipping into often esoteric technologies. Outside of programming, Matthew has a fervent interest in literature.

    After graduating with a computer science degree, he started his career at Sky UK Ltd, where he developed video streaming applications, subsequently moving on to engineer single-page analytics applications at payments startup Velocity. Now he’s working at financial services leader Tradeweb, fleshing out their next-generation JavaScript-based trading platform.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    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.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.

    At www.PacktPub.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.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Preface

    TypeScript allows developers to write readable and maintainable web applications. Editors can provide several tools to the developer, based on types and static analysis of the code. In this book, you will learn how you can use TypeScript to build clean web applications. You will learn how to use Angular 2 and React.

    You will also learn how you can use TypeScript for servers, mobile apps, command-line tools, and games. We will build various servers, write a mobile app, rewrite Pac Man, and build Tic-Tac-Toe as a command-line application. You will also learn functional programming. This style of programming will improve your general code skills. You will see how this style can be used in TypeScript.

    What this book covers

    The book can be divided in two sections. The first section, chapters 1 to 4, describe how you can build standard application. These chapters introduce Angular 2 and React for web applications, NodeJS for servers and NativeScript for mobile apps. You should read chapters 1 to 3 in a sequence.

    The second section, chapters 5 to 8, introduce more complex concepts. You will learn functional programming in chapters 5 to 7. The last chapter contains guidance to migrate a JavaScript codebase to TypeScript. You can read chapters 5 to 7 when you have not read chapters 1 to 4, though chapter 5 requires some knowledge of React.

    Chapter 1, TypeScript 2.0 Fundamentals, will explain core principals to create (web) applications with TypeScript. If you have some basic knowledge of TypeScript 2.0 then you can skim over this chapter or use it as a reference while reading the other chapters. If you have not used TypeScript yet, then this chapter will teach you the fundamentals of TypeScript 2.0

    Chapter 2, A Weather Forecast Widget with Angular 2, you will learn how you can build an application in Angular 2. The chapter introduces core principals of Angular and will use an online API as source for the weather forecast.

    Chapter 3, Note-Taking App with a Server, we will build a server and client with Node and Angular for this application. You will see how code can be shared between the client and the server.

    Chapter 4, Real-Time Chat, introduces React and websockets. Using these techniques, we will write the server and client of the chat application.

    Chapter 5, Native QR Scanner App, after having written three web applications, we will now write a mobile app. You will learn how you can use NativeScript and its plugins to write a native app.

    Chapter 6, Advanced Programming in TypeScript,  covers more advanced features of TypeScript, including type guards, control flow analysis and performance of algorithms.

    Chapter 7, Spreadsheet Applications with Functional Programming, introduces a different programming style: functional programming. You will learn how this can be used in TypeScript. We will use React with a Flux-based architecture, which fits nicely with TypeScript and Functional Programming.

    Chapter 8, Pac Man in HTML5, will show how to use the HTML5 canvas to create a game. We will use some Functional Programming again, and take a look at how we can create a framework for it based on the Flux architecture.

    Chapter 9, Playing Tic-Tac-Toe against an AI, will explain how to build a command-line application in which you can play Tic-Tac-Toe. You will learn how you can learn the computer to play the game. When done correctly, the computer should never lose.

    Chapter 10, Migrate JavaScript to TypeScript, will show how you can incrementally migrate a JavaScript codebase to TypeScript. We will focus on how you can keep the project working during this transition.

    What you need for this book

    You will need an editor to write the code, a terminal to compile the code, and a browser to see the results. Visual Studio Code and Atom with atom-typescript are good editors in which you can write TypeScript code. These are available for Windows, Mac, and Linux. You have to compile TypeScript in a terminal. On Windows, you can use the Command Prompt or Powershell for that. On a Mac, you can use Terminal.

    To compile TypeScript, you need NodeJS. You can find details on how you can install it in the first chapter.

    Chapter 5, Native QR Scanner App, has more requirements to run the mobile app in an emulator or a device. Details about how you can install these dependencies are found in the chapter.

    Who this book is for

    If you are interested in building fun projects using TypeScript, then this book is for you. This book will appeal to web developers who wish to make the most of TypeScript. You should be familiar with the fundamentals of JavaScript.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.

    A block of code is set as follows:

    export function factorial(x: number): number {

       if (x <= 1) return 1;

       return x * factorial(x - 1);

    }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    export function factorial(x: number): number {

       if (x <= 1) return 1;

     

      return x * factorial(x - 1);

     

    }

    Any command-line input or output is written as follows:

    npm init -y

    New terms and important words are shown in bold. 

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    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 at https://github.com/PacktPublishing/TypeScript-Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Downloading the color images of this book 

    We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/TypeScriptBlueprints_ColorImages.pdf.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at copyright@packtpub.com with a link to the suspected pirated material.

    We appreciate your help in protecting

    Enjoying the preview?
    Page 1 of 1