15 Working with JavaScript

 

This chapter covers

  • Adding pure JavaScript code to a TypeScript project
  • Providing type definitions for JavaScript code
  • Enabling type checking for JavaScript code
  • Defining types for third-party packages
  • Using publicly available type definitions
  • Generating type declarations for use in other projects

TypeScript projects generally incorporate some amount of pure JavaScript code, either because the application is written in both TypeScript and JavaScript or because the project relies on third-party JavaScript packages installed using NPM. In this chapter, I describe the features that TypeScript provides for working with JavaScript. Table 15.1 summarizes the chapter.

Table 15.1 Chapter summary (view table figure)

Problem

Solution

Listing

Incorporate JavaScript files in a project

Enable the allowJs and checkJs compiler options

9–13

Control whether a JavaScript file is checked by the TypeScript compiler

Use the @ts-check and @ts-nocheck comments

14

Describe JavaScript types

Use JSDoc comments or create a declaration file

15–22

Describe third-party JavaScript code

Update the compiler configuration and create a declaration file

22–26

Describe third-party code without creating a declaration file

Use a package that contains a declaration file or install a publicly available type declaration package

27–34

Generate declaration files for use in other projects

Enable the declaration compiler option

35–38

15.1 Preparing for this chapter

15.1.1 Adding TypeScript code to the example project

15.2 Working with JavaScript

15.2.1 Including JavaScript in the compilation process

15.2.2 Type-checking JavaScript code

15.3 Describing types used in JavaScript code

15.3.1 Using comments to describe types

15.3.2 Using type declaration files

15.3.3 Describing third-party JavaScript code

15.3.4 Using Definitely Typed declaration files

15.3.5 Using packages that include type declarations

15.4 Generating declaration files

Summary