7 Understanding static types

 

This chapter covers

  • Restricting the range of types that can be as signed to variables or used in operations
  • Relying on the compiler to infer types
  • Using any, never, and unknown types to broaden or restrict the range of values
  • Creating type unions that combine multiple types
  • Using type assertions and type guards to narrow types
  • Controlling how the JavaScript null and undefined values can be used

In this chapter, I introduce the key TypeScript features for working with data types. The features I describe in this chapter are the foundations for working with TypeScript, and they are the building blocks for the advanced features described in later chapters.

I start by showing how TypeScript’s types differ from pure JavaScript’s types. I demonstrate that the TypeScript compiler can infer data types from code, and then I introduce features that provide precise control over data types, either by giving the TypeScript compiler information about how sections of code are expected to behave or by changing the way that the compiler is configured. Table 7.1 summarizes the chapter.

7.1 Preparing for this chapter

7.2 Understanding static types

7.2.1 Creating a static type with a type annotation

7.2.2 Using implicitly defined static types

7.2.3 Using the any type

7.3 Using type unions

7.4 Using Type Assertions

7.4.1 Asserting to an unexpected type

7.5 Using a type guard

7.5.1 Understanding the never type

7.6 Using the unknown type

7.7 Using nullable types

7.7.1 Restricting nullable assignments

7.7.2 Removing null from a union with an assertion

7.7.3 Removing null from a union with a type guard

7.7.4 Using the definite assignment assertion

Summary