Chapter 3. The Type System
In the previous chapter you learned about the basic building blocks that allow you to make your JavaScript code more expressive. But if you are experienced in JavaScript, you understand that TypeScript’s fundamental types and annotations cover only a small set of its inherent flexibility.
TypeScript is supposed to make intentions in JavaScript clearer, and it wants to do so without sacrificing this flexibility, especially since it allowed developers to design fantastic APIs used and loved by millions. Think of TypeScript more as a way to formalize JavaScript, rather than restrict it. Enter TypeScript’s type system.
In this chapter, you will develop a mental model for how to think about types. You will learn how to define sets of values as widely or as narrowly as you need, and how to change their scope throughout your control flow. You will also learn how to leverage a structural type system and when to break with the rules.
This chapter marks the line between TypeScript foundations and advanced type techniques. But whether you are an experienced TypeScript developer or just starting out, this mental model will be the baseline for everything to come.
3.1 Modeling Data with Union and Intersection Types
Problem
You have an elaborate data model you want to describe in TypeScript.
Solution
Use union and intersection types to model your data. Use literal types to define specific variants.
Discussion
Suppose you are creating a data model for a toy shop. ...
Get TypeScript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.