8 Using functions

 

This chapter covers

  • Defining functions with static data types for the parameters and results
  • Working with optional function parameters
  • Defining function parameters with default values
  • Using rest parameters to capture multiple argument values
  • Overloading function types
  • Using assert functions as type guards

In this chapter, I explain how TypeScript is applied to functions, showing you how TypeScript helps prevent common problems when defining functions, dealing with parameters, and producing results. Table 8.1 summarizes the chapter.

Table 8.1 Chapter summary (view table figure)

Problem

Solution

Listing

Allow a function to be called with fewer arguments than parameters

Define optional parameters or define parameters with default values

7, 8

Allow a function to be called with more arguments than parameters

Use a rest parameter

9, 10

Restrict the types that can be used for parameter values and results

Apply type annotations to parameters or function signatures

11, 17, 18

Prevent null values from being used as function arguments

Enable the strictNullChecks compiler option

12–14

Ensure that all function code paths return a result

Enable the noImplicitReturns compiler option

15, 16

Describe the relationship between the types of a function’s parameters and its result

Overload the function’s types

19, 20

Describe the effect of an assert function

Use the assert keyword

21–23

For quick reference, table 8.2 lists the TypeScript compiler options used in this chapter.

8.1 Preparing for this chapter

8.2 Defining functions

8.2.1 Redefining functions

8.2.2 Understanding function parameters

8.2.3 Understanding function results

8.2.4 Overloading function types

8.2.5 Understanding assert functions

Summary