Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
The TypeScript Workshop
The TypeScript Workshop

The TypeScript Workshop: A practical guide to confident, effective TypeScript programming

Arrow left icon
Profile Icon Ben Grynhaus Profile Icon Wekoslav Stefanovski Profile Icon Matt Morgan Profile Icon Rayon Hunte Profile Icon Jordan Hudgens +1 more Show less
Arrow right icon
Can$12.99 Can$44.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (19 Ratings)
eBook Jul 2021 714 pages 1st Edition
eBook
Can$12.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial
Arrow left icon
Profile Icon Ben Grynhaus Profile Icon Wekoslav Stefanovski Profile Icon Matt Morgan Profile Icon Rayon Hunte Profile Icon Jordan Hudgens +1 more Show less
Arrow right icon
Can$12.99 Can$44.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (19 Ratings)
eBook Jul 2021 714 pages 1st Edition
eBook
Can$12.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial
eBook
Can$12.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

The TypeScript Workshop

2. Declaration Files

Overview

This chapter gets you started with declaration files in TypeScript. You will learn how to work with declaration files, including how to build your own declaration files from scratch, and then work with types in external libraries. By the end of this chapter, you will be able to create declaration files from scratch, implement common development patterns for creating declaration files, and produce type checking when working with third-party NPM code libraries.

Introduction

In this chapter, you will learn about TypeScript declaration files. Declaration files give you the ability to give TypeScript more information about how a function or class is structured.

Why is it important to understand how declaration files work? Technically, declaration files speak directly to the core motivations for why TypeScript is becoming so popular. One of the common rationales for using TypeScript is because it guides developers through the application process. Let's walk through a real-world example as a case study.

In pure JavaScript, if we start working with a code library that we've never used before that formats dates, such as Moment JS, we would have to start by looking through the documentation in order to know what type of data we can pass to the Moment JS functions. When working with a new library, it is tedious work to figure out requirements, such as how many function arguments are required for each function and what data type each argument needs to be.

With the declaration files, however, TypeScript informs the text editor of the requirements for every function that a library has. So, instead of having to rely solely on documentation and Google searches, the text editor itself informs the developer how to work with each function. For example, the text editor, with the help of TypeScript, would inform us that the Moment JS format function takes in zero to one arguments, and the optional argument needs to be a string. And declaration files make all of this possible.

Declaration Files

Anytime we're asked to write additional boilerplate code, our first question is: why is it important to do this? With that in mind, before we walk through creating and managing declaration files, let's first analyze the role of declaration files in the development process.

The entire reason why we use TypeScript in the first place is to give our applications a specified structure based on types. Declaration files extend this functionality by allowing us to define the shape of our programs.

In this section, we will walk through two ways to work with declaration files. The first approach will be to create our own declaration files from scratch. This is a great place to start since it provides insight into how the declaration process works. In the second part, we will see how we can integrate types into third-party NPM libraries.

Note

Declaration files are not a new concept in the programming world. The same principle has been used for decades in older programming languages such as Java, C, and C++.

Before we get into this chapter's example project, let's look at the core elements that comprise a declaration file in TypeScript. Consider the following code, which assigns a string value to a variable:

firstName = "Kristine";

The preceding code in TypeScript will generate a compiler warning that says Cannot find name 'firstName', which can be seen in the following screenshot:

Figure 2.1: Compiler error when TypeScript cannot find a variable declaration

Figure 2.1: Compiler error when TypeScript cannot find a variable declaration

This error is shown because whenever we attempt to assign a value to a variable, TypeScript looks for where a variable name is defined. We can fix this by utilizing the declare keyword. The following code will correct the error that we encountered in the previous case:

declare let firstName: string;
firstName = "Kristine";

As you can see in the following screenshot, the compiler warning disappeared with the use of the declare keyword:

Figure 2.2: Example of a variable being defined in TypeScript

Figure 2.2: Example of a variable being defined in TypeScript

Now, that may not seem like a big deal, because we could accomplish the same goal by simply defining a let variable, such as the following:

let firstName: string;
firstName = "Kristine"

The preceding code would not generate an error when viewed in the Visual Studio Code editor.

So, what is the point of using declare? As we build out complex modules, the declare process allows us to describe the complete shape of our modules in a way that cannot be done by simply defining a variable. Now that you know the role of declaration files along with the basic syntax, let's walk through the full workflow of creating a declaration file from scratch in the following exercise.

Exercise 2.01: Creating a Declaration File from Scratch

In this exercise, we'll create a declaration file from scratch. We'll declare file conventions, import, and then use declared files. Consider that you are developing a web app that requires users to register themselves with credentials such as email, user roles, and passwords. The data types of these credentials will be stated in the declaration file that we'll be creating. A user won't be allowed to log in if they fail to enter the correct credentials.

Note

The code files for this exercise can be found here: https://packt.link/bBzat.

Perform the following steps to implement this exercise:

  1. Open the Visual Studio Code editor.
  2. Create a new directory and then create a file named user.ts.
  3. Start the TypeScript compiler and have it watch for changes to the file with the following terminal compile command:
    tsc user.ts ––watch

    The following screenshot shows how the command appears inside the terminal:

    Figure 2.3: Running the TypeScript compiler with the watch flag

    Figure 2.3: Running the TypeScript compiler with the watch flag

    It's fine to leave this file empty for now. We'll start building out our implementation shortly. Now let's create our declaration file.

  4. Create a directory called types/ at the root of our program and then create a file inside it called AuthTypes.d.ts.

    Our project's directory should now look like this:

    Figure 2.4: AuthTypes file structure

    Figure 2.4: AuthTypes file structure

    Note

    Traditionally, declaration files are kept in their own directory called types/ and are then imported by the modules that they are defining. It's also the standard convention to use the file extension of .d.ts instead of .ts for your declaration files.

  5. Within the new declaration file, define the shape of our AuthTypes module. Use the declare keyword at the top of the file. This tells TypeScript that we are about to describe how the AuthTypes module should be structured:
    declare module "AuthTypes" {
        export interface User {
            email: string;
            roles: Array<string>;
        }
    }

    In the preceding code, another bit of syntax that might be different than what you're used to writing is that we wrap the module name in quotation marks. When we implement the program, you'll see that if we remove the quotation marks, we won't be able to import the module. Inside the module, we can place any number of exports that we want the module to have. One of the most important concepts to keep in mind is that declaration files do not have any implementation code; they simply describe the types and structure for the elements used in the module. The following screenshot gives a visual representation of the code:

    Figure 2.5: AuthTypes interface

    Figure 2.5: AuthTypes interface

    The compiler messages suggest that the import should happen successfully as there have not been any errors up to this point.

    In this step, we're exporting a user interface that defines two data points: email and roles. As far as the data types are concerned, the email attribute needs to be a string, and roles needs to be an array filled with strings. Such type definitions will ensure that anyone using this module will be informed immediately if they attempt to use the incorrect data structure.

    Now that we have defined the AuthTypes module, we need to import it into our TypeScript file so that we can use it. We're going to use the reference import process to bring the file into our program.

  6. Go to the user.ts file and add the following two lines of code:
    /// <reference path = "./types/AuthTypes.d.ts" />
    import auth = require("AuthTypes");

    The code in the editor will look something like this:

    Figure 2.6: Importing a declaration file

    Figure 2.6: Importing a declaration file

    The first line in the preceding code will make AuthTypes.d.ts available to our program, and the second line imports the module itself. Obviously, you can use any variable name for the import statement that you prefer. In this code, we're importing the AuthTypes module and storing it in the auth keyword.

    With our module imported, we can now start building the implementation for our program. We'll start out by defining a variable and assigning it to our user interface type that we defined in the declaration files.

  7. Add the following code to the user.ts file:
    let jon: auth.User;

    The updated code of user.ts file will look something like this:

    /// <reference path = "./types/AuthTypes.d.ts" />
    import auth = require("AuthTypes");
    let jon: auth.User;

    What we've done here is quite impressive. We've essentially created our own type/interface in a separate file, imported it, and told the TypeScript compiler that our new variable is going to be of the User type.

  8. Add the actual values of email and roles for the jon variable with the help of the following code:
    jon = {
        email: "jon@snow.com",
        roles: ["admin"]
    };

    With the required shape in place, the program compiles properly, and you can perform any tasks that you need to do.

  9. Create another User and see how we can work with optional attributes. Add the following code to add details of the user alice:
    let alice: auth.User;
    alice = {
        email: "alice@snow.com",
        roles: ["super_admin"]
    };

    Now, let's imagine that we sometimes keep track of how a user found our application. Not all users will have this attribute though, so we'll need to make it optional without breaking the other user accounts. You can mark an attribute as optional by adding a question mark before the colon.

  10. Add a source attribute to the declaration file:
    declare module "AuthTypes" {
        export interface User {
            email: string;
            roles: Array<string>;
            source?: string;
        }
    }
  11. Update our alice user with a source value of facebook:
    /// <reference path = "./types/AuthTypes.d.ts" />
    import auth = require("AuthTypes");
    let jon: auth.User;
    jon = {
        email: "jon@snow.com",
        roles: ["admin"]
    };
    let alice: auth.User;
    alice = {
        email: "alice@snow.com",
        roles: ["super_admin"],
        source: "facebook"
    }

    Notice that the jon variable still works perfectly fine, even without the source value. This helps us to build flexible interfaces for our programs that define both optional and required data points.

  12. Open the terminal and run the following command to generate a JavaScript file:
    tsc user.ts

    Let's now look at the generated user.js file, which can be seen in the following screenshot:

Figure 2.7: Declaration file rules not added to the generated JavaScript code

Figure 2.7: Declaration file rules not added to the generated JavaScript code

Well, that's interesting. There is literally not a single mention of the declaration file in the generated JavaScript code. This brings up a very important piece of knowledge to know when it comes to declaration files and TypeScript in general: declaration files are used solely for the benefit of the developer and are only utilized by the IDE.

Declaration files are completely bypassed when it comes to what is rendered in the program. And with this in mind, hopefully the goal of declaration files is becoming clearer. The better your declaration files are, the easier it will be for the IDE to understand your program and for yourself and other developers to work with your code.

Exceptions

Let's see what happens when we don't follow the rules of our interface. Remember in the previous exercise that our interface required two data elements (email and roles) and that they need to be of the string and Array<string> types. So, watch what happens when we don't implement the proper data type with the following code:

jon = {
    email: 123
}

This will generate the following compiler error, as shown in the following screenshot:

Figure 2.8: TypeScript showing the required data types for an object

Figure 2.8: TypeScript showing the required data types for an object

That is incredibly helpful. Imagine that you are working with a library that you've never used before. If you were using vanilla JavaScript, this implementation would silently fail and would force you to dig through the library's source code to see what structure it required.

This compiler error makes sense, and in a real-life application, such as a React or an Angular app, the application wouldn't even load until the issue was fixed. If we update the data structure to match the declaration file for AuthTypes with the following code:

jon = {
    email: "jon@snow.com"
}

We can see that the compiler will move the error message up to the jon variable name. If you hover over it, or look at the terminal output, you'll see the error shown in the following screenshot:

Figure 2.9: TypeScript showing the required attributes for an object

Figure 2.9: TypeScript showing the required attributes for an object

This is an incredibly useful functionality. If you're new to development, this may not seem like a very big deal. However, this type of information is the exact reason why TypeScript continues to grow in popularity. Error messages such as this instantly provide the information that we need in order to fix the bug and work with the program. In the preceding screenshot, the message is telling us that the program won't compile as we are missing a required value, namely, roles.

Now that we have built out our own declaration file from scratch, it's time to move on and see how declaration files are utilized by other libraries.

Third-Party Code Libraries

Depending on the types of applications that you build, you may never need to build your own declaration files. However, if you're using TypeScript and working with third-party modules, you will need to understand how declaration files work because you will then be able to work seamlessly with external libraries.

DefinitelyTyped

Let's jump back in time for a moment. When TypeScript was originally developed, there was quite a bit of excitement around the idea of integrating types into JavaScript applications. However, developers began to get frustrated, because even though they were building their programs with types, every time that they imported an external library, such as lodash, they were forced to write code with no type signatures and little to no IDE guidance.

Essentially, this meant that each time we were to call a function from an external library, we didn't have a high level of assurance that we were working with it properly.

Thankfully, the open source community had the answer, and the DefinitelyTyped library was created. DefinitelyTyped is a very large repository that contains literally thousands of declaration files for JavaScript code libraries. This means that libraries such as react, lodash, and pretty much every other popular library has a full set of declaration files that we can use in our TypeScript programs.

Note

For more information on DefinitelyTyped, visit https://definitelytyped.org.

Analyzing an External Declaration File

Before we learn how to import and use types with external libraries, let's peek into what they look like:

Figure 2.10: Example of how DefinitelyTyped uses declaration files

Figure 2.10: Example of how DefinitelyTyped uses declaration files

In the preceding screenshot, if you look at the lodash declaration file for the array data structure, you'll see that a single declaration file is over 2,000 lines long. That can be a little intimidating to look at, so let's try to simplify it.

Note

lodash is a utility library that provides functionality for working with objects, strings, arrays, and suchlike. The lodash library's declaration file for the array data structure, as shown in the preceding screenshot, can be found here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/common/array.d.ts.

You'll be pleased to know that the elements in the preceding declaration file are exactly what we built out in Exercise 1.01: Creating a Declaration File from Scratch. It starts by declaring a module instance, and from that point, it lists out interfaces for each of the elements that utilize the array data structure. In fact, if you dissect the code, you'll see that lodash provides three interfaces for each of the functions in the library. You don't have to know what these do; however, it is helpful to realize that you can provide as many interfaces as needed when you're building your own code libraries.

Let's now look at the interface for the last function:

Figure 2.11: How lodash implements interfaces

Figure 2.11: How lodash implements interfaces

This is a good function to look at, because we'll use it when we get to the example for this section. You can see that the majority of the interface is actually a comment. If you've never seen this syntax before, it is using JSDoc syntax. This is very helpful, because IDEs such as Visual Studio Code will pull the comment, parameters, and return type directly into the IntelliSense interface. This means that when we start typing the last function when working with lodash, the IDE will automatically pull in the comment data so we can easily read how to use the function.

After that, the declaration is pretty basic. It simply describes the shape of the last function, specifically, that it takes a list of values as the argument and then returns either T or undefined. Don't worry about all the references to T; you'll learn about what this represents in Chapter 8, Generics. For now, just know that it means that it is returning a value.

Following the same pattern from when we created the declaration file from scratch, in the next section, let's create a new TypeScript project and walk through a practical example of why types are needed.

Exercise 2.02: Creating Types with External Libraries

In this exercise, we'll install types and integrate our types with external libraries. We will also be exploring a scenario wherein we'll check how the function behaves when the wrong type of parameter is passed to it. You'll need to start with an empty directory for this exercise.

Note

The code files for this exercise can be found here: https://packt.link/k7Wbt.

Perform the following steps to implement this exercise:

  1. Open the Visual Studio Code editor.
  2. Create an empty directory on your computer and run the following command to create a new NPM project:
    npm init -y

    The preceding code will generate a package.json file.

  3. To install the Lodash library, open the terminal and type the following command:
    npm i lodash

    The preceding command installs the Lodash library. The package.json file should now look something like this, with lodash installed in the dependencies list:

    Figure 2.12: The generated package.json file

    Figure 2.12: The generated package.json file

  4. Create a file in that directory named lodash_examples.ts, start the TypeScript compiler, and have it watch for changes. Inside of the new .ts file, add the following code:
    import _ = require("lodash");
    const nums = [1, 2, 3];
    console.log(_.last(nums));
  5. Run the preceding program in the terminal by writing the following commands:
    tsc lodash_examples.ts
    node lodash_examples.js

    The console generates an output of 3, as you can see in the following screenshot:

    Figure 2.13: Running the generated lodash_example.js program

    Figure 2.13: Running the generated lodash_example.js program

  6. Create another variable named number and assign it the value 10. We'll then pass this number as an argument to the Lodash library's _.last() function. Write the following code to do this:
    import _ = require("lodash");
    //const nums = [1, 2, 3];
    //console.log(_.last(nums));
    const number = 10;
    console.log(_.last(number));

    Since we've looked at the declaration file, we know that the last function expects an array or some type of list. However, for now, let's pretend that we don't have that information, and this is the first time that we're working with the Lodash library.

    Note

    The Lodash library's last function also works with strings because it views the string of characters like a collection of characters. For example, _.last("hey") will return "y" since it's the last character in the string.

  7. Run the preceding program in the terminal by writing the following commands:
    tsc lodash_examples.ts
    node lodash_examples.js

    The following output is generated when the preceding commands are executed:

    Figure 2.14: What happens when the wrong argument is passed to the last function

    Figure 2.14: What happens when the wrong argument is passed to the last function

    In such a small program, this may seem like a trivial issue. However, in a large system, getting an undefined value while expecting an actual value can be time-consuming, as we have to spend more time on debugging.

    In order to fix this issue, let's leverage the DefinitelyTyped repository and bring in the lodash types. If you hover over the import statement at the top of the file, you'll even see the following warning and recommendation, as shown in the following screenshot:

    Figure 2.15: TypeScript recommending to install Lodash types from DefinitelyTyped

    Figure 2.15: TypeScript recommending to install Lodash types from DefinitelyTyped

    That's quite helpful. The warning itself is showing us how we can install the types for the library.

  8. Follow the recommendation and run the following command in the terminal to install lodash types:
    npm install @types/lodash

    Note

    Any time that you see an install command that starts with @types/, that means that NPM is going to pull from the DefinitelyTyped repository.

    If you run that command, the warning in the import statement should go away automatically. But even more importantly, you should now see that the IDE is now complaining about the line of code where we're trying to pass a number to the last function. If you hover over the word number, you should see the error shown in the following screenshot:

Figure 2.16: IntelliSense revealing the correct type to use with the last function

Figure 2.16: IntelliSense revealing the correct type to use with the last function

From the preceding screenshot, it is clear that the last function won't take any argument of the number type. It accepts either an array or a list as an argument. So, let's imagine that we're building a real-world application, and we try to use the last function. If we were using vanilla JavaScript, we wouldn't realize our error until we, or even a user, encountered the error while running the program. However, by leveraging TypeScript and DefinitelyTyped, the program won't even compile if we attempt to use a function in the incorrect manner.

Development Workflow with DefinitelyTyped

Now that you've seen how to install and work with types, we will walk through a full development workflow so that you can observe the benefits of working with types. Without the integration of types into external libraries, we are forced to either have prior knowledge of the library or dig through the documentation to discover the proper usage.

However, with types, we're going to see how much more streamlined the process is when it comes to working with libraries such as lodash. Let's solve an exercise in the next section to get a proper understanding of this.

Exercise 2.03: Creating a Baseball Lineup Card Application

In this exercise, we'll create a baseball lineup application, wherein we have an array of player names that we'll be retrieving from an API, and then we have a constant variable in the application called lineupOrder. Our lineup card application needs to pair the names from the API with lineupOrder:

Note

The code files for this exercise can be found here: https://packt.link/01spI.

  1. Open the Visual Studio Code editor.
  2. Create a file named lodash_newexamples.ts and add the following code, wherein we have an array variable, playerNames, and a list, lineupOrder:
    import _ = require("lodash");
    const playerNames = [
        "Springer",
        "Bregman",
        "Altuve",
        "Correa",
        "Brantley",
        "White",
        "Gonzalez",
        "Kemp",
        "Reddick"
    ];
    const lineupOrder = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 

    This is a perfect situation for using the zip function from the Lodash library. Let's imagine that we've heard about the zip function, but aren't quite aware of how to use it yet. Start by writing the following code in the same file:

    _.zip()
  3. Once you've typed the preceding code, place the cursor in between the parentheses. You'll get some guidance on how to use the function straight from DefinitelyTyped, as shown in the following screenshot:
    Figure 2.17: IntelliSense guidance on how to use the zip function in lodash

    Figure 2.17: IntelliSense guidance on how to use the zip function in lodash

    Note

    From the preceding screenshot, we can see that the zip function takes two arguments. Both arguments need to be ArrayLike, which means they need to function as a type of collection. Also, the function groups the elements together and returns the grouped collection. Thus, without having to dig through the lodash documentation, we were able to leverage the type definition as we were building the program. It gives us the guidance we need while working with the function.

    Let's now test it out. We know that the zip function takes in two arrays. So, let's provide it with the playerNames and lineupOrder arrays.

  4. Add the following code to provide the zip function with two arrays, playerNames and lineupOrder:
    console.log(_.zip(lineupOrder, playerNames));

    If you run the preceding code, you'll see that the zip function does exactly what it said it would do. It groups the elements and returns the exact data structure that we needed. The rendered lineup card would look something like that shown in the following screenshot:

Figure 2.18: Running the zip function properly from lodash

Figure 2.18: Running the zip function properly from lodash

In completing this process, you can see how DefinitelyTyped allows you to extend types directly into third-party libraries so that you can get type guidance in your programs.

Activity 2.01: Building a Heat Map Declaration File

In this activity, you will build a TypeScript application named heat map log system for tracking baseball pitch data and ensuring data integrity. You will utilize a TypeScript declaration file to build the type system for the program. From that point, you will import the Lodash library and will add type checking to the program by implementing type definitions from DefinitelyTyped.

The steps are as follows:

  1. Visit the following GitHub repository and download the activity project containing the specs and configuration elements: https://packt.link/vnj1R.
  2. Create a file called heat_map_data.ts.
  3. Run the TypeScript compiler on the file and watch for changes.
  4. Create a declaration file and define a module called HeatMapTypes and export the interface named Pitcher.
  5. Define three attributes for the Pitcher module: batterHotZones, pitcherHotZones, and coordinateMap.
  6. The data structures should be the same for all three attributes, Array<Array<number>>, but coordinateMap should be optional.
  7. Then, import the declaration files into the heat_map_data.ts file. Then, create and export a let variable called data and assign it to the Pitcher type.
  8. Add values that adhere to the declaration rules, ensuring that one of the nested arrays is identical in the batterHotZones and pitcherHotZones attributes.
  9. Create a new function called findMatch that takes in both the batterHotZones and pitcherHotZones arrays and utilize the lodash function, intersectionWith, to return the identical nested array. You will need to import the Lodash library, which was installed when you initially ran npm install. Finally, store the value of findMatch in the coordinateMap attribute that was defined in the declaration file.

    The expected output of this activity will be a nested array that looks similar to this:

    [[10.2, -5], [3, 2]]

    Note

    The solution to this activity can be found via this link.

Summary

In this chapter, we've walked through how to utilize declaration files in TypeScript. We've analyzed how declaration files can assist the IDE in guiding how programs should be structured. We've seen examples of structuring the declaration files. Importing declaration files into TypeScript files assists in the development life cycle. We learned to assign objects to custom types that were defined in the declaration files. It injects typed guidance into the IDE's IntelliSense process. We also learned about DefinitelyTyped and how it can be leveraged to layer on types for third-party libraries and work with them like typed programs.

With all this knowledge of declaration files, in the next chapter, we'll be taking a deep dive into working with functions in TypeScript. We'll be defining a function using types, building a suite of functions in a module, building a class of functions to perform a specific task, and exploring unit testing.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Quickly get started writing TypeScript code with hands-on exercises and activities
  • Develop new skills that can be applied at work or in your own side projects
  • Build your understanding, boost your confidence, and advance your programming career

Description

By learning TypeScript, you can start writing cleaner, more readable code that’s easier to understand and less likely to contain bugs. What’s not to like? It’s certainly an appealing prospect, but learning a new language can be challenging, and it’s not always easy to know where to begin. This book is the perfect place to start. It provides the ideal platform for JavaScript programmers to practice writing eloquent, productive TypeScript code. Unlike many theory-heavy books, The TypeScript Workshop balances clear explanations with opportunities for hands-on practice. You’ll quickly be up and running building functional websites, without having to wade through pages and pages of history and dull, dry fluff. Guided exercises clearly demonstrate how key concepts are used in the real world, and each chapter is rounded off with an activity that challenges you to apply your new knowledge in the context of a realistic scenario. Whether you’re a hobbyist eager to get cracking on your next project, or a professional developer looking to unlock your next promotion, pick up a copy and make a start! Whatever your motivation, by the end of this book, you’ll have the confidence and understanding to make it happen with TypeScript.

Who is this book for?

The TypeScript Workshop is for software developers who want to broaden their skill set by learning the TypeScript programming language. To get the most from this TypeScript book, you should have basic knowledge of JavaScript or experience using another similar programming language.

What you will learn

  • Configure a professional TypeScript development environment
  • Explore how to use primitive and complex data types
  • Incorporate types into popular npm (Node package manager) libraries
  • Design systems that use asynchronous behavior
  • Implement object-oriented programming to model real-world scenarios
  • Get to grips with modern UI design by combining React with TypeScript

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 29, 2021
Length: 714 pages
Edition : 1st
Language : English
ISBN-13 : 9781838826765
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 29, 2021
Length: 714 pages
Edition : 1st
Language : English
ISBN-13 : 9781838826765
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 172.97
TypeScript 4 Design Patterns and Best Practices
Can$46.99
The TypeScript Workshop
Can$55.99
Mastering TypeScript
Can$69.99
Total Can$ 172.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. TypeScript Fundamentals Chevron down icon Chevron up icon
2. Declaration Files Chevron down icon Chevron up icon
3. Functions Chevron down icon Chevron up icon
4. Classes and Objects Chevron down icon Chevron up icon
5. Interfaces and Inheritance Chevron down icon Chevron up icon
6. Advanced Types Chevron down icon Chevron up icon
7. Decorators Chevron down icon Chevron up icon
8. Dependency Injection in TypeScript Chevron down icon Chevron up icon
9. Generics and Conditional Types Chevron down icon Chevron up icon
10. Event Loop and Asynchronous Behavior Chevron down icon Chevron up icon
11. Higher-Order Functions and Callbacks Chevron down icon Chevron up icon
12. Guide to Promises in TypeScript Chevron down icon Chevron up icon
13. Async/Await in TypeScript Chevron down icon Chevron up icon
14. TypeScript and React Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(19 Ratings)
5 star 78.9%
4 star 15.8%
3 star 0%
2 star 5.3%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Kiril Zvezdakoski Feb 13, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Natalie Nov 25, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a great comprehensive overview and introduction to TypeScript. There is a lot of real-world examples and information throughout.
Amazon Verified review Amazon
anon Aug 05, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is not another TypeScript cheat sheet.As usual with the "Workshop" line of Packtpub books, it's 100% practice, practice, practice with the needed theory kept to a minimum, although you will learn a lot of interesting concepts from that theory.There are a lot of exercises (guided) and activities (solutions at the end of the book) to train yourself to master TypeScript.I appreciate that the topics are not limited to beginner level (it is covered and goes far beyond), you will practice with:- databases,- REST APIs,- design patterns like Dependency Injection (often not mentioned in many TypeScript books)- mentions about the internals of TypeScript to JavaScript transpilation based on target environment (client and server-side)- advanced typing techniques specific to the TypeScript paradigmIt has sections on Angular and React and Node.js and Nest.js with TypeScript.You will even build an authentication page with Firebase.All in all, a recommended book for hands-on professional TypeScript practices.
Amazon Verified review Amazon
Malik Webster Sep 05, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is well written. It clearly explains what Typescript is, how to use it, and provides working examples. The book is up to date with the latest technologies and current packages, such as VS Code. I saw a few errors with images covering text, but it didn’t distract me too much as I was going through the book. I’d advise those new to TypeScript to pick up this book.
Amazon Verified review Amazon
Luis F Suarez Aug 25, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I enjoyed reading the book, it is not the classic textbook that gets you bored and I plan on using it as a reference in the future.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.