Chapter 3. All About Types
In the last chapter I introduced the idea of type systems, but I never defined what the type in type system really means.
If that sounds confusing, let me give a few familiar examples:
-
The
booleantype is the set of all booleans (there are just two:trueandfalse) and the operations you can perform on them (like||,&&, and!). -
The
numbertype is the set of all numbers and the operations you can perform on them (like+,-, *,/,%,||,&&, and?), including the methods you can call on them like.toFixed,.toPrecision,.toString, and so on. -
The
stringtype is the set of all strings and the operations you can perform on them (like+,||, and&&), including the methods you can call on them like.concatand.toUpperCase.
When you see that something is of type T, not only do you know that it’s a T, but you also know exactly what you can do with that T (and what you can’t). Remember, the whole point is to use the typechecker to stop you from doing invalid things. And the way the typechecker knows what’s valid and what’s not is by looking at the types you’re using and how you’re using them.
In this chapter we’ll take a tour of the types available in TypeScript and cover the basics of what you can do with each of them. Figure 3-1 gives an overview.
Figure 3-1. TypeScript’s type hierarchy
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access