Home Programming The TypeScript Workshop

The TypeScript Workshop

By Ben Grynhaus , Jordan Hudgens , Rayon Hunte and 2 more
books-svg-icon Book
eBook $29.99 $20.98
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    2. Declaration Files
About this book
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.
Publication date:
July 2021
Publisher
Packt
Pages
714
ISBN
9781838828493

 

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.

About the Authors
  • Ben Grynhaus

    Ben Grynhaus is a full-stack developer with a passion for the frontend. With over 7 years of experience, most of them in web development working with various tech stacks, he specializes in TypeScript, React, and Angular. Ben has worked on several products at Microsoft and is now part of an innovative start-up in the marketing domain. He has published numerous open source npm modules that help in Angular app development, especially when integrating with React.

    Browse publications by this author
  • Jordan Hudgens

    Jordan Hudgens is a full-stack developer and the founder of DevCamp and the Bottega Code School. As a developer for over the past 15 years, he specializes in Ruby on Rails, React, Vue.js, and TypeScript with a focus on API development. He has built applications for a wide variety of organizations, including Eventbrite and Quip. He has published and maintains multiple open-source NPM modules that help individuals automate the development process for JavaScript and TypeScript applications. Additionally, he has published over 30 courses, taught 42,000 students globally, and written several programming books.

    Browse publications by this author
  • Rayon Hunte

    Rayon Hunte has been working with Angular and TypeScript for more than 3 years. He has built complex web applications, such as a vehicle management system and a land management web application for the local government. TypeScript has enabled Rayon to leverage his knowledge of JavaScript and web frameworks to build complex, scalable web applications. Having been a development team lead, Rayon has firsthand knowledge of how large projects can become too complicated and impossible to modify and scale as time passes and more features are added. He realizes that adding strong typing to your projects is essential in modern web development and for him, TypeScript has been a real game-changer.

    Browse publications by this author
  • Matt Morgan

    Matt Morgan has been a software engineer, architect, and technology leader for more than 20 years. He's worked with many technologies over the years, such as RDBMS, Java, and Node.js, and seen many generations of web frameworks rise and fall. He is an occasional OSS contributor and a frequent blogger. Matt is most interested in finding ways to improve workflows and developer experience. A great toolchain is a force multiplier.

    Browse publications by this author
  • Vekoslav Stefanovski

    Wekoslav Stefanovski has about two decades of professional developer experience using a variety of development technologies. Has been using JavaScript since the previous millennium and has a long and fruitful love/hate relationship with it. On the other hand, with TypeScript it was love at first compilation, and it's only gotten better since then. His passions include building better programs and building better programmers.

    Browse publications by this author
Latest Reviews (1 reviews total)
The TypeScript Workshop
Unlock this book and the full library FREE for 7 days
Start now