TypeScript: Modern JavaScript Development

Book description

Leverage the features of TypeScript to boost your development skills and create captivating applications

About This Book

  • Learn how to develop modular, scalable, maintainable, and adaptable web applications by taking advantage of TypeScript

  • Explore techniques to use TypeScript alongside other leading tools such as Angular 2, React, and Node.js

  • Focusing on design patterns in TypeScript, this step-by-step guide demonstrates all the important design patterns in practice

  • Who This Book Is For

    This Learning Path is for intermediate-level JavaScript developers who want to use TypeScript to build beautiful web applications and fun projects. No prior knowledge of TypeScript is required, but a basic understanding of jQuery is expected. This Learning Path is also for experienced TypeScript developers who want to take their skills to the next level, and also for web developers who wish to make the most of TypeScript.

    What You Will Learn

  • Understand the key TypeScript language features and runtime

  • Install and configure the necessary tools in order to start developing an application

  • Create object-oriented code that adheres to the SOLID principles

  • Develop robust applications with testing (Mocha, Chai, and SinonJS)

  • Apply GoF patterns in an application with a testing approach

  • Identify the challenges when developing an application

  • Migrate JavaScript codebases to TypeScript to improve your workflow

  • Utilize System.JS and Webpack to load scripts and their dependencies

  • Develop high performance server-side applications to run within Node.js

  • In Detail

    TypeScript is an open source and cross-platform typed superset of JavaScript that compiles to plain JavaScript that runs in any browser or any host. TypeScript adds optional static types, classes, and modules to JavaScript, to enable great tooling and better structuring of large JavaScript applications. Through this three-module learning path, you’ll learn the ins-and-outs of TypeScript for building more robust software.

    The first module gets you started with TypeScript and helps you understand the basics of TypeScript and automation tools. Get a detailed description of function, generics, callbacks, and promises, and discover the object-oriented features and memory management functionality of TypeScript.

    The next module starts by explaining the current challenges when designing and developing an application and how you can solve these challenges by applying the correct design pattern and best practices. You will be introduced to low-level programming concepts to help you write TypeScript code, as well as working with software architecture, best practices, and design aspects.

    The final module will help you build a complete single page app with Angular 2, create a neat mobile app using NativeScript, and even build a Pac Man game with TypeScript. As if the fun wasn't enough, you'll also find out how to migrate your legacy codebase from JavaScript to TypeScript.

    By the end of this Learning Path, you will be able to take your skills up a notch and develop full-fledged web applications using the latest features of the TypeScript.

    This Learning Path combines some of the best that Packt has to offer in one complete, curated package. It includes content from the following Packt products:

  • Learning TypeScript by Remo H. Jansen

  • TypeScript Design Patterns by Vilic Vane

  • TypeScript Blueprints by Ivo Gabe de Wolff

  • Style and approach

    This is a step-by-step, practical guide covering the fundamentals of TypeScript with practical examples. The end-to-end projects included in this book will give you ready-to-implement solutions for your business scenario, showcasing the depth and robustness of TypeScript.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

    Table of contents

    1. TypeScript: Modern JavaScript Development
      1. Table of Contents
      2. TypeScript: Modern JavaScript Development
      3. TypeScript: Modern JavaScript Development
      4. Credits
      5. Preface
        1. What this learning path covers
        2. What you need for this learning path
        3. Who this learning path is for
        4. Reader feedback
        5. Customer support
        6. Downloading the example code
        7. Errata
        8. Piracy
        9. Questions
      6. 1. Module 1
        1. 1. Introducing TypeScript
          1. The TypeScript architecture
            1. Design goals
            2. TypeScript components
          2. TypeScript language features
            1. Types
              1. Optional static type notation
            2. Variables, basic types, and operators
              1. Var, let, and const
              2. Union types
              3. Type guards
              4. Type aliases
              5. Ambient declarations
              6. Arithmetic operators
              7. Comparison operators
              8. Logical operators
              9. Bitwise operators
              10. Assignment operators
            3. Flow control statements
              1. The single-selection structure (if)
              2. The double-selection structure (if…else)
              3. The inline ternary operator (?)
              4. The multiple-selection structure (switch)
              5. The expression is tested at the top of the loop (while)
              6. The expression is tested at the bottom of the loop (do…while)
              7. Iterate on each object's properties (for…in)
              8. Counter controlled repetition (for)
            4. Functions
            5. Classes
            6. Interfaces
            7. Namespaces
          3. Putting everything together
          4. Summary
        2. 2. Automating Your Development Workflow
          1. A modern development workflow
          2. Prerequisites
            1. Node.js
            2. Atom
            3. Git and GitHub
          3. Source control tools
          4. Package management tools
            1. npm
            2. Bower
            3. tsd
          5. Task runners
            1. Checking the quality of the TypeScript code
            2. Compiling the TypeScript code
            3. Optimizing a TypeScript application
            4. Managing the Gulp tasks' execution order
          6. Test runners
          7. Synchronized cross-device testing
          8. Continuous Integration tools
          9. Scaffolding tools
          10. Summary
        3. 3. Working with Functions
          1. Working with functions in TypeScript
            1. Function declarations and function expressions
            2. Function types
            3. Functions with optional parameters
            4. Functions with default parameters
            5. Functions with rest parameters
            6. Function overloading
            7. Specialized overloading signatures
            8. Function scope
            9. Immediately invoked functions
            10. Generics
            11. Tag functions and tagged templates
          2. Asynchronous programming in TypeScript
            1. Callbacks and higher-order functions
            2. Arrow functions
            3. Callback hell
            4. Promises
            5. Generators
            6. Asynchronous functions – async and await
          3. Summary
        4. 4. Object-Oriented Programming with TypeScript
          1. SOLID principles
          2. Classes
          3. Interfaces
          4. Association, aggregation, and composition
            1. Association
            2. Aggregation
            3. Composition
          5. Inheritance
            1. Mixins
          6. Generic classes
          7. Generic constraints
            1. Multiple types in generic type constraints
            2. The new operator in generic types
          8. Applying the SOLID principles
            1. The Liskov substitution principle
            2. The interface segregation principle
            3. The dependency inversion principle
          9. Namespaces
          10. Modules
            1. ES6 modules – runtime and design time
            2. External modules – design time only
            3. AMD modules – runtime only
            4. CommonJS modules – runtime only
            5. UMD modules – runtime only
            6. SystemJS modules – runtime only
          11. Circular dependencies
          12. Summary
        5. 5. Runtime
          1. The environment
          2. The runtime
            1. Frames
            2. Stack
            3. Queue
            4. Heap
            5. The event loop
          3. The this operator
            1. The this operator in the global context
            2. The this operator in a function context
            3. The call, apply, and bind methods
          4. Prototypes
            1. Instance properties versus class properties
            2. Prototypal inheritance
            3. The prototype chain
            4. Accessing the prototype of an object
            5. The new operator
          5. Closures
            1. Static variables with closures
            2. Private members with closures
          6. Summary
        6. 6. Application Performance
          1. Prerequisites
          2. Performance and resources
          3. Performance metrics
            1. Availability
            2. The response time
            3. Processing speed
            4. Latency
            5. Bandwidth
            6. Scalability
          4. Performance analysis
            1. Network performance analysis
            2. Network performance and user experience
              1. Network performance best practices and rules
            3. GPU performance analysis
              1. Frames per second (FPS)
            4. CPU performance analysis
            5. Memory performance analysis
            6. The garbage collector
          5. Performance automation
            1. Performance optimization automation
            2. Performance monitoring automation
            3. Performance testing automation
          6. Exception handling
            1. The Error class
            2. The try…catch statements and throw statements
          7. Summary
        7. 7. Application Testing
          1. Software testing glossary
            1. Assertions
            2. Specs
            3. Test cases
            4. Suites
            5. Spies
            6. Dummies
            7. Stubs
            8. Mocks
            9. Test coverage
          2. Prerequisites
            1. Gulp
            2. Karma
            3. Istanbul
            4. Mocha
            5. Chai
            6. Sinon.JS
            7. Type definitions
            8. PhantomJS
            9. Selenium and Nightwatch.js
          3. Testing planning and methodologies
            1. Test-driven development
            2. Behavior-driven development (BDD)
            3. Tests plans and test types
          4. Setting up a test infrastructure
            1. Building the application with Gulp
            2. Running the unit test with Karma
            3. Running E2E tests with Selenium and Nightwatch.js
          5. Creating test assertions, specs, and suites with Mocha and Chai
            1. Testing the asynchronous code
            2. Asserting exceptions
            3. TDD versus BDD with Mocha and Chai
          6. Test spies and stubs with Sinon.JS
            1. Spies
            2. Stubs
          7. Creating end-to-end tests with Nightwatch.js
          8. Generating test coverage reports
          9. Summary
        8. 8. Decorators
          1. Prerequisites
          2. Annotations and decorators
            1. The class decorators
            2. The method decorators
            3. The property decorators
            4. The parameter decorators
            5. The decorator factory
            6. Decorators with arguments
            7. The reflection metadata API
          3. Summary
        9. 9. Application Architecture
          1. The single-page application architecture
          2. The MV* architecture
          3. Common components and features in the MV* frameworks
            1. Models
            2. Collections
            3. Item views
            4. Collection views
            5. Controllers
            6. Events
            7. Router and hash (#) navigation
            8. Mediator
            9. Dispatcher
            10. Client-side rendering and Virtual DOM
            11. User interface data binding
              1. One-way data binding
              2. Two-way data binding
            12. Data flow
            13. Web components and shadow DOM
          4. Choosing an application framework
          5. Writing an MVC framework from scratch
            1. Prerequisites
            2. Application events
            3. Mediator
            4. Application
            5. Route
            6. Event emitter
            7. Router
            8. Dispatcher
            9. Controller
            10. Model and model settings
            11. View and view settings
            12. Framework
          6. Summary
        10. 10. Putting Everything Together
          1. Prerequisites
          2. The application's requirements
          3. The application's data
          4. The application's architecture
          5. The application's file structure
          6. Configuring the automated build
          7. The application's layout
          8. Implementing the root component
          9. Implementing the market controller
          10. Implementing the NASDAQ model
          11. Implementing the NYSE model
          12. Implementing the market view
          13. Implementing the market template
          14. Implementing the symbol controller
            1. Implementing the quote model
          15. Implementing the symbol view
          16. Implementing the chart model
          17. Implementing the chart view
          18. Testing the application
          19. Preparing the application for a production release
          20. Summary
      7. 2. Module 2
        1. 1. Tools and Frameworks
          1. Installing the prerequisites
            1. Installing Node.js
            2. Installing TypeScript compiler
          2. Choosing a handy editor
            1. Visual Studio Code
              1. Configuring Visual Studio Code
              2. Opening a folder as a workspace
              3. Configuring a minimum build task
            2. Sublime Text with TypeScript plugin
              1. Installing Package Control
              2. Installing the TypeScript plugin
            3. Other editor or IDE options
              1. Atom with the TypeScript plugin
              2. Visual Studio
              3. WebStorm
          3. Getting your hands on the workflow
            1. Configuring a TypeScript project
              1. Introduction to tsconfig.json
              2. Compiler options
                1. target
                2. module
                3. declaration
                4. sourceMap
                5. jsx
                6. noEmitOnError
                7. noEmitHelpers
                8. noImplicitAny
                9. experimentalDecorators*
                10. emitDecoratorMetadata*
                11. outDir
                12. outFile
                13. rootDir
                14. preserveConstEnums
                15. strictNullChecks
                16. stripInternal*
                17. isolatedModules
              3. Adding source map support
            2. Downloading declarations using typings
              1. Installing typings
              2. Downloading declaration files
              3. Option "save"
            3. Testing with Mocha and Istanbul
              1. Mocha and Chai
                1. Writing tests in JavaScript
                2. Writing tests in TypeScript
              2. Getting coverage information with Istanbul
            4. Testing in real browsers with Karma
              1. Creating a browser project
              2. Installing Karma
              3. Configuring and starting Karma
            5. Integrating commands with npm
            6. Why not other fancy build tools?
          4. Summary
        2. 2. The Challenge of Increasing Complexity
          1. Implementing the basics
            1. Creating the code base
            2. Defining the initial structure of the data to be synchronized
            3. Getting data by comparing timestamps
            4. Two-way synchronizing
            5. Things that went wrong while implementing the basics
              1. Passing a data store from the server to the client does not make sense
              2. Making the relationships clear
          2. Growing features
            1. Synchronizing multiple items
              1. Simply replacing data type with an array
              2. Server-centered synchronization
                1. Synchronizing from the server to the client
                2. Synchronizing from client to server
            2. Synchronizing multiple types of data
            3. Supporting multiple clients with incremental data
              1. Updating the client side
              2. Updating server side
            4. Supporting more conflict merging
              1. New data structures
              2. Updating client side
              3. Updating the server side
            5. Things that go wrong while implementing everything
              1. Piling up similar yet parallel processes
              2. Data stores that are tremendously simplified
          3. Getting things right
            1. Finding abstraction
            2. Implementing strategies
            3. Wrapping stores
          4. Summary
        3. 3. Creational Design Patterns
          1. Factory method
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          2. Abstract Factory
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          3. Builder
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          4. Prototype
          5. Singleton
            1. Basic implementations
            2. Conditional singletons
          6. Summary
        4. 4. Structural Design Patterns
          1. Composite Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          2. Decorator Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
              1. Classical decorators
              2. Decorators with ES-next syntax
            4. Consequences
          3. Adapter Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          4. Bridge Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          5. Façade Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          6. Flyweight Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          7. Proxy Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          8. Summary
        5. 5. Behavioral Design Patterns
          1. Chain of Responsibility Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          2. Command Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          3. Memento Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          4. Iterator Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
              1. Simple array iterator
              2. ES6 iterator
            4. Consequences
          5. Mediator Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          6. Summary
        6. 6. Behavioral Design Patterns: Continuous
          1. Strategy Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          2. State Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          3. Template Method Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          4. Observer Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          5. Visitor Pattern
            1. Participants
            2. Pattern scope
            3. Implementation
            4. Consequences
          6. Summary
        7. 7. Patterns and Architectures in JavaScript and TypeScript
          1. Promise-based web architecture
            1. Promisifying existing modules or libraries
            2. Views and controllers in Express
            3. Abstraction of responses
            4. Abstraction of permissions
            5. Expected errors
              1. Defining and throwing expected errors
              2. Transforming errors
          2. Modularizing project
          3. Asynchronous patterns
            1. Writing predictable code
            2. Asynchronous creational patterns
            3. Asynchronous middleware and hooks
            4. Event-based stream parser
          4. Summary
        8. 8. SOLID Principles
          1. Single responsibility principle
            1. Example
            2. Choosing an axis
          2. Open-closed principle
            1. Example
            2. Abstraction in JavaScript and TypeScript
            3. Refactor earlier
          3. Liskov substitution principle
            1. Example
            2. The constraints of substitution
          4. Interface segregation principle
            1. Example
            2. Proper granularity
          5. Dependency inversion principle
            1. Example
            2. Separating layers
          6. Summary
        9. 9. The Road to Enterprise Application
          1. Creating an application
            1. Decision between SPA and "normal" web applications
            2. Taking team collaboration into consideration
          2. Building and testing projects
            1. Static assets packaging with webpack
              1. Introduction to webpack
              2. Bundling JavaScript
              3. Loading TypeScript
              4. Splitting code
              5. Loading other static assets
            2. Adding TSLint to projects
            3. Integrating webpack and tslint command with npm scripts
          3. Version control
            1. Git flow
              1. Main branches
              2. Supporting branches
                1. Feature branches
                2. Release branches
                3. Hotfix branches
              3. Summary of Git flow
            2. Pull request based code review
              1. Configuring branch permissions
              2. Comments and modifications before merge
            3. Testing before commits
              1. Git hooks
              2. Adding pre-commit hook automatically
          4. Continuous integration
            1. Connecting GitHub repository with Travis-CI
          5. Deployment automation
            1. Passive deployment based on Git server side hooks
            2. Proactive deployment based on timers or notifications
          6. Summary
      8. 3. Module 3
        1. 1. TypeScript 2.0 Fundamentals
          1. What is TypeScript?
          2. Quick example
            1. Transpiling
            2. Type checking
          3. Learning modern JavaScript
            1. let and const
            2. Classes
            3. Arrow functions
            4. Function arguments
            5. Array spread
            6. Destructuring
            7. Template strings
            8. New classes
          4. Type checking
            1. Primitive types
            2. Defining types
            3. Undefined and null
            4. Type annotations
          5. Summary
        2. 2. A Weather Forecast Widget with Angular 2
          1. Using modules
          2. Setting up the project
            1. Directory structure
            2. Configuring TypeScript
            3. Building the system
            4. The HTML file
          3. Creating the first component
            1. The template
            2. Testing
            3. Interactions
            4. One-way variable binding
            5. Event listeners
          4. Adding conditions to the template
            1. Directives
            2. The template tag
            3. Modifying the about template
          5. Using the component in other components
          6. Showing a forecast
            1. Using the API
            2. Typing the API
          7. Creating the forecast component
            1. Templates
            2. Downloading the forecast
            3. Adding @Output
          8. The main component
            1. Using our other components
            2. Two-way bindings
            3. Listening to our event
            4. Geolocation API
            5. Component sources
          9. Summary
        3. 3. Note-Taking App with a Server
          1. Setting up the project structure
            1. Directories
            2. Configuring the build tool
            3. Type definitions
          2. Getting started with NodeJS
            1. Asynchronous code
              1. Callback approach for asynchronous code
              2. Disadvantages of callbacks
            2. The database
              1. Wrapping functions in promises
              2. Connecting to the database
              3. Querying the database
          3. Understanding the structural type system
            1. Generics
            2. Typing the API
          4. Adding authentication
            1. Implementing users in the database
            2. Adding users to the database
          5. Testing the API
          6. Adding CRUD operations
            1. Implementing the handlers
            2. Request handling
          7. Writing the client side
            1. Creating the login form
            2. Creating a menu
            3. The note editor
            4. The main component
              1. Error handler
          8. Running the application
          9. Summary
        4. 4. Real-Time Chat
          1. Setting up the project
            1. Configuring gulp
          2. Getting started with React
            1. Creating a component with JSX
            2. Adding props and state to a component
            3. Creating the menu
            4. Testing the application
          3. Writing the server
            1. Connections
            2. Typing the API
            3. Accepting connections
            4. Storing recent messages
            5. Handling a session
            6. Implementing a chat message session
          4. Connecting to the server
            1. Automatic reconnecting
            2. Sending a message to the server
            3. Writing the event handler
          5. Creating the chat room
            1. Two-way bindings
            2. Stateless functional components
            3. Running the application
          6. Comparing React and Angular
            1. Templates and JSX
            2. Libraries or frameworks
          7. Summary
        5. 5. Native QR Scanner App
          1. Getting started with NativeScript
          2. Creating the project structure
            1. Adding TypeScript
          3. Creating a Hello World page
          4. Creating the main view
          5. Adding a details view
          6. Scanning QR codes
            1. Type definitions
            2. Implementation
            3. Testing on a device
          7. Adding persistent storage
          8. Styling the app
          9. Comparing NativeScript to alternatives
          10. Summary
        6. 6. Advanced Programming in TypeScript
          1. Using type guards
            1. Narrowing
            2. Narrowing any
            3. Combining type guards
          2. More accurate type guards
            1. Assignments
          3. Checking null and undefined
            1. Guard against null and undefined
            2. The never type
          4. Creating tagged union types
          5. Comparing performance of algorithms
            1. Big-Oh notation
            2. Optimizing algorithms
            3. Binary search
            4. Built-in functions
          6. Summary
        7. 7. Spreadsheet Applications with Functional Programming
          1. Setting up the project
          2. Functional programming
            1. Calculating a factorial
          3. Using data types for expressions
            1. Creating data types
            2. Traversing data types
            3. Validating an expression
            4. Calculating expressions
          4. Parsing an expression
            1. Creating core parsers
            2. Running parsers in a sequence
            3. Parsing a number
            4. Order of operations
          5. Defining the sheet
            1. Calculating all fields
          6. Using the Flux architecture
            1. Defining the state
            2. Creating the store and dispatcher
          7. Creating actions
            1. Adding a column or a row
            2. Changing the title
            3. Showing the input popup
            4. Testing actions
          8. Writing the view
            1. Rendering the grid
            2. Rendering a field
            3. Showing the popup
            4. Adding styles
            5. Gluing everything together
          9. Advantages of Flux
            1. Going cross-platform
          10. Summary
        8. 8. Pac Man in HTML5
          1. Setting up the project
          2. Using the HTML5 canvas
            1. Saving and restoring the state
          3. Designing the framework
            1. Creating pictures
            2. Wrapping other pictures
            3. Creating events
            4. Binding everything together
          4. Drawing on the canvas
          5. Adding utility functions
          6. Creating the models
            1. Using enums
            2. Storing the level
            3. Creating the default level
            4. Creating the state
          7. Drawing the view
          8. Handling events
            1. Working with key codes
          9. Creating the time handler
          10. Running the game
          11. Adding a menu
            1. Changing the model
            2. Rendering the menu
            3. Handling events
            4. Modifying the time handler
          12. Summary
        9. 9. Playing Tic-Tac-Toe against an AI
          1. Creating the project structure
            1. Configure TypeScript
          2. Adding utility functions
          3. Creating the models
            1. Showing the grid
            2. Creating operations on the grid
            3. Creating the grid
            4. Adding tests
            5. Random testing
          4. Implementing the AI using Minimax
            1. Implementing Minimax in TypeScript
            2. Optimizing the algorithm
          5. Creating the interface
            1. Handling interaction
            2. Creating players
          6. Testing the AI
            1. Testing with a random player
          7. Summary
        10. 10. Migrate JavaScript to TypeScript
          1. Gradually migrating to TypeScript
          2. Adding TypeScript
            1. Configuring TypeScript
            2. Configuring the build tool
            3. Acquiring type definitions
            4. Testing the project
          3. Migrating each file
            1. Converting to ES modules
            2. Correcting types
            3. Adding type guards and casts
            4. Using modern syntax
            5. Adding types
          4. Refactoring the project
            1. Enable strict checks
          5. Summary
      9. A. Bibliography
      10. Index

    Product information

    • Title: TypeScript: Modern JavaScript Development
    • Author(s): Remo H. Jansen, Vilic Vane, Ivo Gabe de Wolff
    • Release date: December 2016
    • Publisher(s): Packt Publishing
    • ISBN: 9781787289086