TypeScript - Numbers: A Comprehensive Guide for Beginners

Hello there, future coding superstar! Welcome to our journey into the world of TypeScript numbers. As your friendly neighborhood computer teacher, I'm here to guide you through this exciting topic. Don't worry if you've never written a line of code before – we'll start from the very beginning and work our way up. So, grab a cup of coffee (or your favorite beverage), and let's dive in!

TypeScript - Numbers

What are Numbers in TypeScript?

Before we get into the nitty-gritty, let's talk about what numbers are in TypeScript. In the programming world, numbers are one of the most fundamental data types. They're like the building blocks of mathematics in our code. TypeScript, being a superset of JavaScript, handles numbers in a similar way but with some added benefits.

Syntax: How to Write Numbers in TypeScript

In TypeScript, you can write numbers in several ways. Let's look at some examples:

let age: number = 30;
let price: number = 19.99;
let billion: number = 1e9;
let hexColor: number = 0xffffff;
let binaryValue: number = 0b1010;
let octalValue: number = 0o744;

Let's break these down:

  • age: A simple integer.
  • price: A decimal number (also called a floating-point number).
  • billion: Scientific notation (1 billion).
  • hexColor: Hexadecimal notation (white color in RGB).
  • binaryValue: Binary notation (equals 10 in decimal).
  • octalValue: Octal notation (equals 484 in decimal).

Remember, in TypeScript, all numbers are floating-point values. This means that even if you write an integer like 30, it's stored as 30.0 behind the scenes.

Creating Number Types

In TypeScript, you can explicitly declare a variable as a number type. This is one of the key features that sets TypeScript apart from JavaScript – it allows us to add type annotations to our variables.

let score: number;
score = 95;

let temperature: number = -5;

function calculateArea(width: number, height: number): number {
    return width * height;
}

let area = calculateArea(10, 20);
console.log(area); // Output: 200

In this example, we've declared score and temperature as number types. We've also created a function calculateArea that takes two number parameters and returns a number. This helps catch errors early if we accidentally try to pass in a string or any other type.

Creating Number Objects

While it's not common (or recommended) in everyday coding, you can also create number objects using the Number constructor:

let numObject: Number = new Number(42);
console.log(typeof numObject); // Output: object

let primitiveNum: number = 42;
console.log(typeof primitiveNum); // Output: number

Notice the capital 'N' in Number when we use the constructor. This creates an object wrapper around the number, which is different from the primitive number type (lowercase 'n'). In most cases, you'll want to use the primitive type for better performance and simpler code.

Number Properties

TypeScript inherits several useful properties from JavaScript's Number object. These are static properties, which means you don't need to create an instance of a Number to use them.

Here's a table of the most common Number properties:

Property Description Example
Number.MAX_VALUE The largest representable number console.log(Number.MAX_VALUE);
Number.MIN_VALUE The smallest representable positive number console.log(Number.MIN_VALUE);
Number.NaN Not-A-Number value console.log(Number.NaN);
Number.NEGATIVE_INFINITY Negative infinity console.log(Number.NEGATIVE_INFINITY);
Number.POSITIVE_INFINITY Positive infinity console.log(Number.POSITIVE_INFINITY);

Let's see these in action:

console.log(Number.MAX_VALUE); // Output: 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // Output: 5e-324
console.log(Number.NaN); // Output: NaN
console.log(Number.NEGATIVE_INFINITY); // Output: -Infinity
console.log(Number.POSITIVE_INFINITY); // Output: Infinity

These properties can be incredibly useful when you need to check for extreme values or special cases in your calculations.

Number Methods

TypeScript numbers also come with a set of built-in methods that can help you perform various operations. Here's a table of some commonly used methods:

Method Description Example
toFixed() Formats a number with a specific number of decimal places let pi = 3.14159; console.log(pi.toFixed(2));
toPrecision() Formats a number to a specified length let bigNumber = 1234.5678; console.log(bigNumber.toPrecision(5));
toString() Converts a number to a string let num = 42; console.log(num.toString());
valueOf() Returns the primitive value of a Number object let numObj = new Number(42); console.log(numObj.valueOf());

Let's see these methods in action:

let pi = 3.14159;
console.log(pi.toFixed(2)); // Output: "3.14"

let bigNumber = 1234.5678;
console.log(bigNumber.toPrecision(5)); // Output: "1234.6"

let num = 42;
console.log(num.toString()); // Output: "42"

let numObj = new Number(42);
console.log(numObj.valueOf()); // Output: 42

These methods can be incredibly helpful when you need to format numbers for display or convert them for different operations.

Conclusion

Whew! We've covered a lot of ground today, from the basics of number syntax in TypeScript to more advanced concepts like Number properties and methods. Remember, working with numbers is a fundamental skill in programming, and mastering these concepts will serve you well in your coding journey.

As we wrap up, here's a little coding humor for you: Why do programmers prefer dark mode? Because light attracts bugs! ?

Keep practicing, stay curious, and don't be afraid to experiment with these number concepts in your own code. Before you know it, you'll be calculating and manipulating numbers like a pro! Until next time, happy coding!

Credits: Image by storyset