Book Image

Learning TypeScript

By : Remo H. Jansen
Book Image

Learning TypeScript

By: Remo H. Jansen

Overview of this book

<p>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. It allows developers to use the future versions of JavaScript (ECMAScript 6 and 7) today. TypeScript adds optional static types, classes, and modules to JavaScript, to enable great tooling and better structuring of large JavaScript applications.</p> <p>This book is a step-by-step guide that will get you started with TypeScript with the help of practical examples. You start off by understanding the basics of TypeScript. Next, automation tools like Grunt are explained followed by a detailed description of function, generics, callbacks and promises. After this, object-oriented features and the memory management functionality of TypeScript are explained. At the end of this book, you will have learned enough to implement all the concepts and build a single page application from scratch.</p>
Table of Contents (18 chapters)
Learning TypeScript
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Asynchronous programming in TypeScript


Now that we have seen how to work with functions, we will explore how we can use them, together with some native objects, to write asynchronous applications.

Callbacks and higher-order functions

In TypeScript, functions can be passed as arguments to another function. The function passed to another as an argument is known as a callback. Functions can also be returned by another function. The functions that accept functions as parameters (callbacks) or return functions as an argument are known as higher-order functions. Callbacks are usually anonymous functions.

var foo = function() { // callback
  console.log('foo');
}

function bar(cb : () => void) { // higher order function
  console.log('bar');
  cb();
}

bar(foo); // prints 'bar' then prints 'foo'

Arrow functions

In TypeScript, we can declare a function using a function expression or an arrow function. An arrow function expression has a shorter syntax compared to function expressions and lexically...