Chapter 2. The Type System
JavaScript’s power
Comes from flexibility
Be careful with that!
I talked briefly in Chapter 1, “From JavaScript to TypeScript” about the existence of a “type checker” in TypeScript that looks at your code, understands how it’s meant to work, and lets you know where you might have messed up. But how does a type checker work, really?
What’s in a Type?
A “type” is a description of what a JavaScript value shape might be.
By “shape” I mean which properties and methods exist on a value, and what the built-in typeof operator would describe it as.
For example, when you create a variable with the initial value "Aretha":
letsinger="Aretha";
TypeScript can infer, or figure out, that the singer variable is of type string.
The most basic types in TypeScript correspond to the seven basic kinds of primitives in JavaScript:
-
null -
undefined -
boolean//trueorfalse -
string//"","Hi!","abc123", … -
number//0,2.1,-4, … -
bigint//0n,2n,-4n, … -
symbol//Symbol(),Symbol("hi"), …
For each of these values, TypeScript understands the type of the value to be one of the seven basic primitives:
-
null; // null -
undefined; // undefined -
true; // boolean -
"Louise"; // string -
1337; // number -
1337n; // bigint -
Symbol("Franklin"); // symbol
If you ever forget the name of a primitive, you can type a let variable with a primitive value into the TypeScript Playground or an IDE and hover your mouse over the variable’s name. The resultant popover ...