All lessons

Numbers & Math

6 min · TypeScript

Do math, with number types keeping you honest.

TypeScript · Numbers & Math0/5 cleared

Enemy 1 of 5

This code multiplies price by quantity, both typed as number, and prints the result. TypeScript stops you from putting a string in either one later. Press Run to see it.

Why this works

A value typed as number can be added, subtracted, multiplied (*), and divided (/), the same arithmetic operators plain JavaScript uses, following the same order of operations (multiplication and division before addition and subtraction, unless parentheses say otherwise).

Store the parts in variables typed as number, then combine them. Because the type is explicit here, TypeScript guarantees that price and quantity can never accidentally hold a string later on. If some other part of the program tried to assign price = "5";, the compiler would reject it immediately.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.