TypeScript Arithmetic Operators: The Definitive Guide
TypeScript didn’t reinvent JavaScript’s arithmetic — it just gave you a seatbelt. Under the hood, every +, -, *, /, and ** behaves exactly like in JavaScript, including all the quirky coercion rules that have launched a thousand memes. What TypeScript adds is the ability to catch those bugs at compile time instead of 3 a.m. when a user enters “banana” in a price field. This guide covers every arithmetic operator in TypeScript with modern, real-world examples, in-depth explanations, common pitfalls, performance notes, and a cheat-sheet you’ll actually use. 1. Unary Operators Unary Plus + Purpose: Explicitly converts its operand to a number using the same algorithm as Number() but much faster. +"42"; // 42 +"3.14"; // 3.14 +""; // 0 (empty string → 0) +" 123 "; // 123 (trims whitespace!) +"0xFF"; // 255 (recognizes hex) +"abc"; // NaN +true; // 1 +false; // 0 +null; // 0 +undefined; // NaN (compile error if strictNullChecks is on)