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 "Chai":

image.png

TypeScript can infer, or figure out, that the singer variable is of type string.

image.png

image.png

If you ever forget the name of a basic type in TypeScript, just create a let or const variable and assign it a value (like a number, string, etc.) in the TypeScript Playground or your code editor. Then, hover your mouse over the variable’s name a small popup will appear showing the type of that value.

image.png

TypeScript is smart enough to figure out the type of a variable based on the value it’s assigned even if the value is calculated. For example, in the code below, TypeScript sees that the result of the expression is always a number, so it automatically sets the type of the cups variable to number:

let cups = Math.random() > 0.5 ? 10 : 5;

Now, open the TypeScript Playground or your IDE, and hover your mouse over the cups variable. You'll see a small tooltip showing that TypeScript has inferred its type as number.

let cups: number;
let cups = Math.random() > 0.5 ? 10 : 5;

image.png


Type Systems